# -*- coding: utf-8 -*-

# Copyright (C) 2013 Sylvain Boily <sboily@proformatique.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import json
from datetime import datetime
from flask.ext.login import login_required
from xivo_admin.extensions import mongo
from actions import ivrActions
from dialplan import Dialplan
from flask import (
     Blueprint,
     render_template,
     url_for,
     request,
     redirect,
     flash,
     Response
)

ivr = Blueprint('ivr', __name__, template_folder='templates',
                            static_folder='static', static_url_path='/%s' % __name__)

@ivr.route('/ivr')
@login_required
def index():
    ivr = mongo.db.ivr.find()
    return render_template('ivr.html', ivr=ivr)

@ivr.route('/ivr/add')
@login_required
def add():
    actions = ivrActions()
    return render_template('ivr_add.html', actions=json.loads(actions.getJsonactions()))

@ivr.route('/ivr/save', methods=['POST'])
@login_required
def save():
    content = request.json
    url_redirect = False
    if not content:
        content = json.load(request.files['my_file'].stream)
        url_redirect = True

    name = content['name']
    content.update({"created_time": datetime.utcnow()})
    if mongo.db.ivr.find_one({"name": name}):
        mongo.db.ivr.update({'name': name},
                            {'$set': content}
                           )
    else:
        mongo.db.ivr.save(content) 
    if url_redirect:
        flash('Upload is completed !')
        return redirect(url_for("ivr.index"))
    return 'IVR save'

@ivr.route('/ivr/show/<ObjectId:id>')
@login_required
def show(id):
    d = Dialplan(mongo.db.ivr.find_one(id)) 
    return d.generate()

@ivr.route('/ivr/export/<ObjectId:id>')
@login_required
def export(id):
    ivr = mongo.db.ivr.find_one_or_404(id)
    export = { "name" : ivr['name'],
               "context" : ivr['context'],
               "nodes" : ivr['nodes'],
               "connections" : ivr['connections'],
               "is_edit" : "add"
              }

    return Response(json.dumps(export),
                    mimetype="application/json",
                    headers={"Content-Disposition":
                             "attachment;filename=ivr.txt"})

@ivr.route('/ivr/shows')
@login_required
def shows():
    ivrs = mongo.db.ivr.find()
    content = '; Produce by XiVO cloud IVR<br>'
    for ivr in ivrs:
        d = Dialplan(ivr)
        content += d.generate()

    return content

@ivr.route('/ivr/check/<ObjectId:id>')
@login_required
def check(id):
    return "Congrats ! You're dialplan is correct, \
            there is no error ! <br><strong>BUT</strong> there is no check for the moment ;-)"

@ivr.route('/ivr/edit/<ObjectId:id>')
@login_required
def edit(id):
    node = mongo.db.ivr.find_one_or_404(id)
    actions = ivrActions()
    if not node:
        flash('Sorry the is no IVR !')
        return redirect(url_for("ivr.index"))
    return render_template('ivr_edit.html', name=node['name'], nodes=node['nodes'], \
                                            connections=node['connections'], \
                                            context=node['context'], \
                                            actions=json.loads(actions.getJsonactions()), id=id)

@ivr.route('/ivr/delete/<ObjectId:id>')
@login_required
def delete(id):
    mongo.db.ivr.remove(id)
    flash('Ivr deleted')
    return redirect(url_for("ivr.index"))
