starter.factory('Schedule', function ($resource, $cordovaCalendar, $q, cfg, formatFilter, showPopup) {
    var schedule = {};
    var recurrenceByDayData = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'];
    var week = ['日', '一', '二', '三', '四', '五', '六'];
    
    function getRecurrenceByDay (days) {
        var arr = [];
        _.each(days, function (item) {
            arr.push(recurrenceByDayData[item])
        })
        return arr.join(',');
    }
    
    function createEventOptions (content, start_date, end_date, repeat_type, freq, notification_type) {
        var options = {
            title: content,
            notes: 'Linker+',
            startDate: new Date(start_date),
            endDate: new Date(start_date)
        }
        
        if (repeat_type == 1) {
            options.recurrence = 'daily';
            options.recurrenceInterval = freq;
        } else if (repeat_type == 2) {
            options.recurrence = 'weekly';
            options.recurrenceByDay = getRecurrenceByDay(freq);
        } else if (repeat_type == 3) {
            options.recurrence = 'monthly'
            options.recurrenceByMonthDay = freq.join(',');
        } else if (repeat_type == 4) {
            options.recurrence = 'yearly'
        }
        
        if (notification_type == 1) {
            options.firstReminderMinutes = 0;
        } else if (notification_type == 2) {
            options.firstReminderMinutes = 5;
        } else if (notification_type == 3) {
            options.firstReminderMinutes = 15;
        } else if (notification_type == 4) {
            options.firstReminderMinutes = 30;
        } else if (notification_type == 5) {
            options.firstReminderMinutes = 60;
        } else if (notification_type == 6) {
            options.firstReminderMinutes = 120;
        } else if (notification_type == 7) {
            options.firstReminderMinutes = 300;
        }
        
        if (end_date) {
            if (!(end_date instanceof Date)) {
            	end_date = new Date(end_date);
            }
            options.recurrenceEndDate = end_date;
        }
        
        return options;
    }
    
    schedule.scheduleDetails = {};
    
    schedule.schedule = $resource(formatFilter('{0}schedule/schedule/:id/', cfg.api));
    schedule.schedulemember = $resource(formatFilter('{0}schedule/schedule/:id/', cfg.api));
    
    schedule.notificationType = {
        "0":"不提醒",
        "1":"事件发生时",
        "2":"提前5分钟",
        "3":"提前15分钟",
        "4":"提前30分钟",
        "5":"提前1小时",
        "6":"提前2小时",
        "7":"提前5小时"
    }
    
    schedule.repeatType = {
        "0":"永不",
        "1":"每天",
        "2":"每周",
        "3":"每月",
        "4":"每年"
    }

    schedule.weekDay = {
        "1":"周一",
        "2":"周二",
        "3":"周三",
        "4":"周四",
        "5":"周五",
        "6":"周六",
        "0":"周日"
    }
    
    schedule.checkSchedule = function (schedules) {
        if (schedules.content == null && schedules.content == '') {
            showPopup.PopupWindow(0, '请输入日程内容', false);
            return false;
//      } else if (schedules.schedulemembers.length == 0) {
//          showPopup.PopupWindow(0, '请选择成员', false);
//          return false;
        } else {
            return true;
        }
    }
    
    schedule.createEventWithOptions = function (content, start_date, end_date, repeat_type, freq, notification_type) {
        var deferred = $q.defer();
        var options = createEventOptions(content, start_date, end_date, repeat_type, freq, notification_type);
        $cordovaCalendar.createEventWithOptions(options).then(function (result) {
            deferred.resolve(true);
        }, function (err) {
            showPopup.PopupWindow(0, '日程创建失败，请重试');
            deferred.resolve(false);
        });
        return deferred.promise;
    }
    
    schedule.deleteEvent = function (content, start_date) {
        var deferred = $q.defer();
        var options = createEventOptions(content, start_date);
        options.endDate = options.endDate.setMonth(options.endDate.getMonth() + 1);
        $cordovaCalendar.deleteEvent(options);
    }
    
    schedule.getRepeatFreqTitle = function (type, freq) {
        var title = '';
        //0:永不,1:每天 2:每周,3:每月,4:每年
        if (typeof freq === 'string')
        	freq = freq.split(',');
        if (type == '0') {
            title = '不重复';
        } else if (type == '1') {
            title = '每' + freq + '天一次';
        } else if (type == '2') {
            _.each(freq, function (item) {
                title += '周' + week[item] + '、';
            })
            title = '每' + title.substring(0, title.lastIndexOf('、'));
        } else if (type == '3') {
            _.each(freq, function (item) {
                title += item + '日、';
            })
//          title = '每月' + freq.join('日、');
            title = '每月' + title.substring(0, title.lastIndexOf('、'));
        } else if (type == '4') {
            title = '每年';
        }
        return title;
    }
    
    schedule.getDateTimeTitle = function (date) {
        var title = '';
        if (!(date instanceof Date))
        	date = new Date(date);
        var minutes_str = date.getMinutes().toString();
        var hours_str = date.getHours().toString();
        if (parseInt(minutes_str) < 10) {
            minutes_str = '0' + minutes_str;
        }
        if (parseInt(hours_str) < 10) {
            hours_str = '0' + hours_str;
        }
        year_str = date.getFullYear() + '年';
        title = year_str + (date.getMonth() + 1) + '月' + date.getDate() + '日 ' + ' 周' + week[date.getDay()] + ' ' + hours_str + ':' + minutes_str;
        return title;
    }
    
    schedule.getMemberTitle = function (member) {
        return _.map(member, function(user) {
            return user.username;
        }).join('、');
    }
    
    return schedule;
});