/**
 * session-controller.js
 * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Contact:
 * DongHee Yang <donghee.yang@samsung.com>
 * Sungmin Kim <sm.art.kim@samsung.com>
 * Jiil Hyoun <jiil.hyoun@samsung.com>
 * Jonghwan Park <iwin100.park@samsung.com>
 * Kitae Kim <kt920.kim@samsung.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors:
 * - S-Core Co., Ltd
**/

define([
    'javascripts/message-dialog.js',
    'dojo/store/Memory',
    'dojo/store/Observable',
    'dojo/request',
    'dojo/cookie'],
    function (MessageDialog, Memory, Observable, request, cookie) {

        function SessionController() {
            var self = this;
            this.store = new Observable(new Memory());

            // load user info from cookie
            var user = cookie('session.user.email');
            var admin = cookie('session.user.admin') || 'false';
            if (user !== undefined) {
                self.store.put({
                    id: 'user',
                    email: user,
                    admin: admin
                });
            } else {
                self.store.put({
                    id: 'user',
                    email: 'anonymous'
                });
            }

            this.signup = function (email, name, password, passwordConfirm, callback) {
                createAccount(email, name, password, passwordConfirm, function (err) {
                    callback(err);
                });
            };

            this.login = function (email, password, callback) {
                createSession(email, password, function (status, res) {
                    var user = JSON.parse(res);
                    switch (status) {
                    case 200:
                        self.store.put({
                            id: 'user',
                            email: email,
                            admin: user.admin
                        });
                        cookie('session.user.email', email, {});
                        cookie('session.user.admin', user.admin, {});
                        break;
                    case 401:
                        console.error('Incorrect password');
                        break;
                    case 404:
                        console.error('Invaild email');
                        break;
                    default:
                        console.error('Error server');
                        break;
                    }
                    callback(status, res);
                });
            };


            this.logout = function (callback) {
                async.series([
                    function (cb) {
                        deleteSession(function (status, res) {
                            switch (status) {
                            case 200:
                                console.log(res);
                                break;
                            default:
                                console.error('Error server');
                                break;
                            }
                            cb(null);
                        });
                    },
                    function (cb) {
                        var dialog = new MessageDialog('Session is fired', {
                            title: 'Log out'
                        });
                        dialog.show();
                        cb(null);
                    },
                    function (cb) {
                        self.expireSession();
                        cb(null);
                    }], function (err) {
                    callback(err);
                });
            };

            this.getCookie = function (key) {
                var cook = document.cookie + ';';
                var idx = cook.indexOf(key, 0);
                var val = '';

                if (idx != -1) {
                    cook = cook.substring(idx, cook.length);
                    begin = cook.indexOf('=', 0) + 1;
                    end = cook.indexOf(';', begin);
                    val = unescape(cook.substring(begin, end));
                }
                return val;
            };

            this.saveCookie = function (key, value, expire_days) {
                var today = new Date();
                today.setDate(today.getDate() + expire_days);
                document.cookie = key + '=' + escape(value) + '; path=/; expires=' + today.toGMTString() + ';';
            };


            this.expireSession = function () {
                self.store.put({
                    id: 'user',
                    email: 'anonymous'
                });
                cookie('session.user.info', null, {
                    expires: -1
                });
                location.replace('index.html');
            };


            function createAccount(email, name, password, passwordConfirm, callback) {
                request.post('signup', {
                    handlelAs: 'json',
                    data: JSON.stringify({
                        email: email,
                        name: name,
                        password: password,
                        passwordConfirm: passwordConfirm
                    }),
                    headers: {
                        'Content-Type': 'application/json; charset=utf-8'
                    }
                }).then(
                    function (response) {
                        callback(null);
                    }, function (err) {
                        callback(err.response.data);
                    });
            }

            function createSession(email, password, callback) {
                request.post('login', {
                    handlelAs: 'json',
                    data: JSON.stringify({
                        email: email,
                        password: password
                    }),
                    headers: {
                        'Content-Type': 'application/json; charset=utf-8'
                    }
                }).then(
                    function (response) {
                        callback(200, response);
                    }, function (err) {
                        callback(err.response.status, null);
                    });
            }


            function deleteSession(callback) {
                request.del('logout', {
                    handlelAs: 'json',
                    headers: {
                        'Content-Type': 'application/json; charset=utf-8'
                    }
                }).then(
                    function (response) {
                        console.log(response);
                        callback(200, response);
                    },
                    function (err) {
                        callback(err.response.status, null);
                    });
            }
        }

        return new SessionController();
    });
