from corrdb.common import logAccess, logStat, logTraffic, crossdomain, basicAuthSession
from corrdb.common.models import UserModel
from corrdb.common.models import ApplicationModel
from corrdb.common.models import ProjectModel
from corrdb.common.models import EnvironmentModel
from corrdb.common.models import RecordModel
from corrdb.common.models import TrafficModel
from corrdb.common.models import StatModel
from corrdb.common.models import VersionModel
from corrdb.common.models import BundleModel
from flask.ext.stormpath import user
from flask.ext.stormpath import login_required
from flask.ext.api import status
import flask as fk
from cloud import app, cloud_response, storage_manager, access_manager, CLOUD_URL, VIEW_HOST, VIEW_PORT, MODE, ACC_SEC, CNT_SEC
import datetime
import simplejson as json
import traceback
import smtplib
from email.mime.text import MIMEText
import mimetypes

@app.route(CLOUD_URL + '/private/env/remove/<env_id>', methods=['GET','POST','PUT','UPDATE','DELETE','POST', 'OPTIONS'])
@crossdomain(fk=fk, app=app, origin='*')
def env_remove(env_id):
    logTraffic(CLOUD_URL, endpoint='/private/env/remove/<env_id>')
    hash_session = basicAuthSession(fk.request)     
    if fk.request.method in ['GET', 'DELETE']:
        access_resp = access_manager.check_cloud(hash_session, ACC_SEC, CNT_SEC)
        current_user = access_resp[1]
        if current_user is None:
            return fk.Response('Unauthorized action on this environment.', status.HTTP_401_UNAUTHORIZED)
        else:
            try:
                logAccess(CLOUD_URL, 'cloud', '/private/env/remove/<env_id>')
                env = EnvironmentModel.objects.with_id(env_id)
            except:
                print(str(traceback.print_exc()))
            if env is None:
                return fk.Response('Unable to find this environment.', status.HTTP_404_NOT_FOUND)
            else:
                # result = storage_manager.delete_env_files(env)
                # if result:
                # implement project history en removal: project.history.append(str(env.id))
                
                count = 0
                for project in ProjectModel.objects(owner=current_user):
                    try:
                        project.history.remove(str(env_id))
                        project.save()
                        count = count + 1
                    except:
                        pass
                if count > 0:
                    env.delete()
                return cloud_response(200, 'Deletion succeeded', 'The environment %s was succesfully deleted.'%env_id)
    else:
       return fk.Response('Endpoint does not support this HTTP method.', status.HTTP_405_METHOD_NOT_ALLOWED)


@app.route(CLOUD_URL + '/private/env/view/<env_id>', methods=['GET','POST','PUT','UPDATE','DELETE','POST', 'OPTIONS'])
@crossdomain(fk=fk, app=app, origin='*')
def env_view(env_id):
    logTraffic(CLOUD_URL, endpoint='/private/env/view/<env_id>')
    hash_session = basicAuthSession(fk.request)
    if fk.request.method == 'GET':
        caccess_resp = access_manager.check_cloud(hash_session, ACC_SEC, CNT_SEC)
        current_user = access_resp[1]
        if current_user is not None:
            try:
                logAccess(CLOUD_URL, 'cloud', '/private/env/view/<env_id>')
                env = EnvironmentModel.objects.with_id(env_id)
                # Make sure user own or used this environment.
                owned = False
                for project in ProjectModel.objects(owner=current_user):
                    if str(env.id) in project.history:
                        owned = True
                        break
                if not owned:
                    env = None
            except:
                env = None
                print(str(traceback.print_exc()))
            if env is None:
                return fk.Response('Unable to find this environment.', status.HTTP_404_NOT_FOUND)
            else:
                return fk.Response(env.to_json(), mimetype='application/json')
        else:
            return fk.Response('Unauthorized action on this environment.', status.HTTP_401_UNAUTHORIZED)
    else:
        return fk.Response('Endpoint does not support this HTTP method.', status.HTTP_405_METHOD_NOT_ALLOWED)

@app.route(CLOUD_URL + '/private/env/create/<record_id>', methods=['GET','POST','PUT','UPDATE','DELETE','POST', 'OPTIONS'])
@crossdomain(fk=fk, app=app, origin='*')
def env_create(record_id):
    logTraffic(CLOUD_URL, endpoint='/private/env/create/<record_id>')
    hash_session = basicAuthSession(fk.request)
    if fk.request.method == 'POST':
        access_resp = access_manager.check_cloud(hash_session, ACC_SEC, CNT_SEC)