var RealtimePanel = function (parent) {
    this.Parent = parent;
    this.ResultList = new ResultList(this, '#realtime-result-list');

    this.TaskInfo = null;
    this.TaskStateCheckTimer = null;

    this.Startup = function () {
        this.ResultList.Startup();
        this.InitReleaseTime();

        $('#calc-btn').on('click', this.OnCalcButtonClick.bind(this));
        $('#reset-btn').on('click', this.OnResetButtonClick.bind(this));
        $('#add-label').on('click', this.OnAddLabelButtonClick.bind(this));
        $('.type-select span').on('click', this.OnTypeSelectClick.bind(this));
    };

    this.InitReleaseTime = function () {
        $('#release-date').datetimebox({
            panelWidth: 190,
            panelHeight: 230,
            panelAlign: 'right',
            showSeconds: false,
            currentText: '现在'
        });
    };

    this.OnCalcButtonClick = function () {
        // Close details
        this.ResultList.Reset();

        // Submit task
        this.TaskInfo = {
            Id: this.CreateId(),
            Result: null,
            CreateTime: new Date()
        };

        // Submit task
        if (Config.InProductionMode)
            this.SubmitTask(this.TaskInfo.Id);
        else
            this.SubmitTest(this.TaskInfo.Id, 36.538, 64.850);
    };

    this.OnResetButtonClick = function () {
        this.Reboot('success', null);
    };

    this.OnAddLabelButtonClick = function () {
        var value = $('#label-input').val().trim();
        if (value.length === 0)
            return;

        $.ajax({
            type: "POST",
            dataType: 'json',
            data: {
                userId: parseInt($('#user-info').attr('userid')),
                taskId: this.TaskInfo.Id,
                name: value
            },
            url: '/Menggu/AddTag',
            success: function (result) {
                var label = $('<a href="javascript:;" tagId="{0}">{1}<span class="clear-btn"><i></i></span></a>'.format(result, value));
                label.on('click', this.SetActiveLabel.bind(this));
                label.find('.clear-btn').on('click', this.RemoveLabel.bind(this));

                $('#realtime-slider').find('.label-list:first').append(label);
                this.Relayout();
            }.bind(this)
        });
    };

    this.CheckTaskState = function () {
        $.ajax({
            type: "GET",
            dataType: 'json',
            url: this.getCheckUrl(this.TaskInfo.Id),
            success: function (result) {
                this.TaskInfo.Result = result;

                if (result.code === 200) {
                    this.AddTask(this.TaskInfo.Id);
                    this.LoadData(result);
                    this.TaskStopped();
                }
                else if (this.IsTaskTimeout()) {
                    this.Reboot("error", "任务计算已超时,请重新提交计算。");
                    this.TaskStopped();
                }
            }.bind(this)
        });
    };

    this.getCheckUrl = function (taskId) {
        if (Config.InProductionMode)
            return 'http://{0}/mg/check?num={1}'.format(Config.ApiRoot, taskId);
        else
            return '/Content/json/menggu/check.json'.format(taskId);
    };

    this.getJsonUrl = function (taskId) {
        if (Config.InProductionMode)
            return "http://{0}/mg/getresult/{1}.json".format(Config.ApiRoot, taskId);
        else
            return '/Content/json/menggu/{0}.json'.format(taskId);
    };

    this.LoadData = function (result) {
        $.getJSON(this.getJsonUrl(result.num), function (data) {
            var param = this.GetTaskParams(this.TaskInfo.Id);
            this.Parent.Map.LoadAverageData('realtime-layer', {
                ReleaseTime: param.releaseTime,
                Longitude: param.longitude,
                Latitude: param.latitude,
                Height: param.height
            }, data);
            this.ResultList.SetData('realtime-layer', [lat, lng], data);
        }.bind(this));
    };

    this.Reboot = function (type, text) {
        $.ajax({
            type: "GET",
            dataType: 'json',
            url: 'http://{0}/mg/reboot'.format(Config.ApiRoot),
            success: function (data) {
                this.MessageBox(type, text !== null ? text : data.info);
            }.bind(this)
        });
    };

    this.TaskStarted = function (taskId) {
        this.TaskStateCheckTimer = setInterval(this.CheckTaskState.bind(this), 10000);
        $('#task-id-span').text(taskId);
        $('.shade').show();
    };

    this.TaskStopped = function () {
        clearInterval(this.TaskStateCheckTimer);
        $('.shade').hide();
    };

    this.CreateId = function () {
        var time = this.GetReleaseTime();
        time = time.replace(new RegExp('-', 'g'), "");

        var now = new Date();
        return time + now.getMilliseconds();
    };

    this.IsTaskTimeout = function () {
        var fromTime = this.TaskInfo.CreateTime.getTime();
        var toTime = (new Date).getTime();
        var seconds = (toTime - fromTime) / 1000;
        return seconds > 600;
    };

    this.GetCalcPramas = function (taskId) {
        var type = $('.type-select span.active').attr('type');
        var lngDegree = $('#lng-degree').val();
        var lngMinute = $('#lng-minute').val();
        var lngSecond = $('#lng-second').val();
        var latDegree = $('#lat-degree').val();
        var latMinute = $('#lat-minute').val();
        var latSecond = $('#lat-second').val();

        return {
            lon: type === 'decimal' ? $('#longitude').val() : this.getLngLat(lngDegree, lngMinute, lngSecond),
            lat: type === 'decimal' ? $('#latitude').val() : this.getLngLat(latDegree, latMinute, latSecond),
            num: taskId,
            hgt: $('#height').val(),
            rlen: $('#time-length-input').val(),
            tlen: $('#interval-length-input').val(),
            tpoint: this.GetReleaseTime()
        };
    };

    this.GetTaskParams = function (taskId) {
        var type = $('.type-select span.active').attr('type');
        var lngDegree = $('#lng-degree').val();
        var lngMinute = $('#lng-minute').val();
        var lngSecond = $('#lng-second').val();
        var latDegree = $('#lat-degree').val();
        var latMinute = $('#lat-minute').val();
        var latSecond = $('#lat-second').val();

        return {
            taskId: taskId,
            region: 'mg',
            longitude: type === 'decimal' ? $('#longitude').val() : this.getLngLat(lngDegree, lngMinute, lngSecond),
            latitude: type === 'decimal' ? $('#latitude').val() : this.getLngLat(latDegree, latMinute, latSecond),
            height: $('#height').val(),
            simulatedDuration: $('#time-length-input').val(),
            simulatedInterval: $('#interval-length-input').val(),
            releaseTime: $("#release-date").datetimebox('getValue'),
            resultState: this.TaskInfo.Result.code,
            resultMessage: this.TaskInfo.Result.code === '200' ? '成功' : this.TaskInfo.Result.info
        };
    };

    this.GetReleaseTime = function () {
        var time = $('#release-date').datetimebox('getValue');
        return moment(time).format('YYYY-MM-DD-HH-mm');
    };

    this.SubmitTask = function (taskId) {
        var params = this.GetCalcPramas(taskId);
        var partten = 'http://{0}/mg/{1}?lon={2}&lat={3}&num={4}&hgt={5}&rlen={6}&tlen={7}&tpoint={8}';
        var url = partten.format(Config.ApiRoot, 'backward', params.lon, params.lat, params.num, params.hgt, params.rlen, params.tlen, params.tpoint);

        $.ajax({
            type: "GET",
            dataType: 'json',
            url: url,
            beforeSend: function () {
                this.TaskStarted(taskId);
            }.bind(this),
            success: function (result) {
                this.TaskStopped();
                this.MessageBox("warning", result.info);
                this.Parent.HistoryPanel.ReloadDataGrid();
            }.bind(this),
            complete: function () {
                $('.param-label').removeClass('label-shade');
            }.bind(this)
        });
    };

    this.SubmitTest = function (taskId, lat, lon) {
        $.ajax({
            type: "GET",
            dataType: 'json',
            url: this.getCheckUrl(taskId),
            success: function (result) {
                this.TaskInfo.Id = taskId;
                this.TaskInfo.Result = result;

                this.Parent.Map.CenterMap(lat, lon);
                this.AddTask(this.TaskInfo.Id);
                this.LoadData(result);
            }.bind(this)
        });
    };

    this.AddTask = function (taskId) {
        $.ajax({
            type: "POST",
            dataType: 'json',
            url: '/Menggu/AddTask',
            data: this.GetTaskParams(taskId),
            success: function (result) {
                console.log(result);
            }.bind(this)
        });
    };

    this.MessageBox = function (type, text) {
        swal({
            title: "",
            text: text,
            type: type,
            icon: type,
            showCancelButton: false,
            confirmButtonText: "确定",
            closeOnConfirm: true
        });
    };

    this.SetActiveLabel = function (event) {
        $(event.target).toggleClass('active');
    };

    this.RemoveLabel = function (event) {
        if ($(event.target).parent().is('a'))
            $(event.target).parent().remove();
        else
            $(event.target).parents('a').remove();
        this.Relayout();
    };

    this.Relayout = function () {
        var windowHeight = $(window).height();
        var labelHeight = $('#realtime-slider').find('.label-list:first').height();

        var resultList = $('#realtime-result-list');
        resultList.find('.calc-list ul').height(windowHeight - labelHeight - 635);
    };

    this.getLngLat = function (degree, minute, second) {
        var str = parseFloat(minute) + parseFloat(second / 60);
        var value = parseFloat(str / 60) + parseFloat(degree);
        return value;
    };

    this.OnTypeSelectClick = function (event) {
        $('.type-select span').removeClass("active");
        $(event.target).addClass("active");

        if ($(event.target).attr('type') === 'decimal') {
            $('#lng-decimal').show();
            $('#lat-decimal').show();
            $('#lng-degrees').hide();
            $('#lat-degrees').hide();
        } else {
            $('#lng-decimal').hide();
            $('#lat-decimal').hide();
            $('#lng-degrees').show();
            $('#lat-degrees').show();
        }
    };
};