import { fromJS } from 'immutable';
const { Seq ,List} = require('immutable')
import OccurrencesInput from './OccurrencesInput.js';
import EndsOnDateTimeWidget from './EndsOnDateTimeWidget.js';
import moment from 'moment';

const initialState = fromJS({
	formData:{
		'eventType':'SCHEDULED',
		"eventUserType": "PILOT",
		'schedule':'',
		'endTimestamp':null,
		'groupId':null,
		'notificationTemplateId':null,
		'startTimestamp':null,
		'allowedOccurances':null,
		'createdBy':null,
		'lastUpdatedBy':null,
		'conditionalScheduleType':null,
		"conditionsTree": null,
		"sqlLogic": null,
		"draftSaved":false
	},
	enableNext:false,
	formErrors:[],
	UserActionSelection:false,
	UserInActionSelection:false,
	RepeatEveryData:[],
	secondaryView:null,
	RepeatOnWeekDays:[],
	ScheduleTime:null,
	RepeatEverySelectedData:null,
	RepeatType:null,
	draftSaved:false,
	selectedDayOfMonth:null,
	RepeatOnWeekDayData:[
		{label: 'Sunday', value: 'SUN', selected:false},
		{label: 'Monday', value: 'MON', selected:false},
		{label: 'Tuesday', value: 'TUE', selected:false},
		{label: 'Wednesday', value: 'WED', selected:false},
		{label: 'Thursday', value: 'THU', selected:false},
		{label: 'Friday', value: 'FRI', selected:false},
		{label: 'Saturday', value: 'SAT', selected:false}
	],
	repeatFrequencyData:[
		{value:'MONTH',label:'Month'},
		{value:'WEEK',label:'Week'},
		{value:'DAILY',label:'Daily'}
	],
	EndNotificationOptions:[
		// {label: 'After', value: 'AFTER', selected:false,checkedComponent:OccurrencesInput},
		{label: 'On', value: 'ON', selected:false,checkedComponent:EndsOnDateTimeWidget}
	],
	RepeatByDayOfMonthOrWeekData:[
		{label: 'Day of the month', value: 'DAY_OF_MONTH', selected:false}
		// {label: 'Day of the week', value: 'DAY_OF_WEEK', selected:false}
	],
	userTriggeredEvents:[
				{
				    'eventName': 'Whenever user does’nt do',
				    'eventType': 'ACTION',
				    'eventValues':[
				        {
				            label:'action 1',
				            value:'ACTION 1',
				            selected:false
				        },
				        {
				            label:'action 2',
				            value:'ACTION 1',
				            selected:false
				        },
				        {
				            label:'action 3',
				            value:'ACTION 3',
				            selected:false
				        }
				    ]
				},
				{
				    'eventName': 'Within (min)',
				    'eventType': 'ACTION',
				    'eventValues':[
				        {
				            label:'action 1',
				            value:'ACTION 1',
				            selected:false
				        },
				        {
				            label:'action 2',
				            value:'ACTION 1',
				            selected:false
				        },
				        {
				            label:'action 3',
				            value:'ACTION 3',
				            selected:false
				        }
				    ]
				},
				{
				    'eventName': 'Send PM after (min)',
				    'eventType': 'ACTION',
				    'eventValues':[
				        {
				            label:'action 1',
				            value:'ACTION 1',
				            selected:false
				        },
				        {
				            label:'action 2',
				            value:'ACTION 1',
				            selected:false
				        },
				        {
				            label:'action 3',
				            value:'ACTION 3',
				            selected:false
				        }
				    ]
				},
				{
				    'eventName': 'From - To',
				    'eventType': 'INACTION',
				    'eventValues':[
				        {
				            label:'inaction 1',
				            value:'INACTION 1',
				            selected:false
				        },
				        {
				            label:'inaction 2',
				            value:'INACTION 2',
				            selected:false
				        },
				        {
				            label:'inaction 3',
				            value:'INACTION 3',
				            selected:false
				        },
				    ]
				}

			]
})

const validationArray = [
	{	
		'campaignName':{
			required:true,
			length:200
		}
	},
	{
		'notificationTitle':{
			required:true,
			length:200
		}
	},
	{
		'notificationContent':{
			required:true,
			length:500
		}
	},
	{
		'notificationAction':{
			required:true
		}
	},
	{
		'notificationType':{
			required:true
		}
	}
]

function createCronExpression(state){
	var data = state.toJS();
	var cronExpression = ["*","*","*","*","*","*","*"];
	debugger
	if(data.ScheduleTime){
		var hour = data.ScheduleTime.format('h');
		var minute = data.ScheduleTime.format('mm');
		var second = data.ScheduleTime.format('ss');
		var amPm = data.ScheduleTime.format('a');
		var date =  data.ScheduleTime.format('DD');
		var month = data.ScheduleTime.format('MM');
		var year = data.ScheduleTime.format('YYYY');
		if(amPm=='pm'){
			hour = parseInt(hour)+12;
		}
		if(amPm=='am' && parseInt(hour)==12){
			hour = 0;
		}
		cronExpression[0] = second;
		cronExpression[1] = minute;
		cronExpression[2] = hour;
		cronExpression[3] = date;
		cronExpression[4] = month;
		cronExpression[6] = year;
	}
	var targetIndex = null;
	switch(data.RepeatType){
		case 'DAILY':
			cronExpression[3]='*';
			cronExpression[4]='*';
			cronExpression[5]='?';
			cronExpression[6]='*';
			break;
		case 'WEEK':
			targetIndex = 5;
			cronExpression[3] = '?';
			cronExpression[4] = '*';
			cronExpression[5] = '*';
			cronExpression[6] = '*';
			var selectedDays = data.RepeatOnWeekDayData.filter((el)=>{
				return el.selected;
			})
			if(data.RepeatEverySelectedData && selectedDays.length>1){
				if(data.RepeatEverySelectedData == 'EVERY_WEEK'){
					cronExpression[targetIndex] = selectedDays[0].value;
				}
				else{
					cronExpression[targetIndex] = (selectedDays[0].value+'#'+data.RepeatEverySelectedData.split('_')[0]);
				}
				var daysArr = [];
				selectedDays.forEach((el,i)=>{
					if(data.RepeatEverySelectedData == 'EVERY_WEEK'){
						daysArr.push(el.value);
					}
					else{
						daysArr.push(el.value+'#'+data.RepeatEverySelectedData.split('_')[0]);
					}
				})
				cronExpression[targetIndex] = daysArr.join(',');
			}
			else if(data.RepeatEverySelectedData && selectedDays.length == 1){
				if(data.RepeatEverySelectedData == 'EVERY_WEEK'){
					cronExpression[targetIndex] = selectedDays[0].value;
				}
				else{
					cronExpression[targetIndex] = (selectedDays[0].value+'#'+data.RepeatEverySelectedData.split('_')[0]);
				}
			}
			else{
				cronExpression[targetIndex] = '*';
			}
			break;
		case 'MONTH':
			targetIndex = 4;
			cronExpression[5] = '*';
			cronExpression[6] = '*';
			if(data.RepeatEverySelectedData && (data.RepeatEverySelectedData != 'EVERY_MONTH')){
				cronExpression[targetIndex] = ('1/'+data.RepeatEverySelectedData.split('_')[0]);
			}
			else if(data.RepeatEverySelectedData == 'EVERY_MONTH'){
				cronExpression[targetIndex] = '1/1';
				cronExpression[5] = '?';
				cronExpression[0]=(cronExpression[0]=='*')?0:cronExpression[0];
				cronExpression[1]=(cronExpression[1]=='*')?0:cronExpression[1];
				cronExpression[2]=(cronExpression[2]=='*')?0:cronExpression[2];
			}
			else{
				cronExpression[targetIndex] = '*';
			}
			var selectedOption = data.RepeatByDayOfMonthOrWeekData.filter((el)=>{
				return (el.selected);
			})
			if(selectedOption[0] && selectedOption[0].value=='DAY_OF_MONTH' && data.ScheduleTime){
				targetIndex = 3;
				cronExpression[targetIndex] = data.ScheduleTime.format('DD');
				cronExpression[5] = '?';
			}
			if(selectedOption[0] && selectedOption[0].value=='DAY_OF_WEEK' && data.ScheduleTime){
				targetIndex = 5;
				cronExpression[targetIndex] = data.ScheduleTime.format('ddd')+"#1"
				cronExpression[3] = '?';
			}
			break;
		case 'YEAR':
			targetIndex = 6;
			if(data.RepeatEveryData){
				cronExpression[targetIndex] = ('1/'+data.RepeatEverySelectedData.split('_')[0]);
				cronExpression[3] = data.ScheduleTime.format('DD');
				cronExpression[4] = data.ScheduleTime.format('MM');
				cronExpression[5] = '?'
			}
			else{
				cronExpression[targetIndex] = '*';
			}
			break;
	}
	var expression = cronExpression.join(' ');
	return expression;

}

export const whenReducer = function (state=initialState, action) {
	switch(action.type){
		case 'START_NOW_FLOW':
			var newState = state.setIn(['formData','conditionalScheduleType'],action.data);
			newState = newState.setIn(['formData','startTimestamp'],(new moment().unix()));
			newState = newState.setIn(['formData','endTimestamp'],null)
			newState = newState.set('enableNext', true);
			return newState.set('ScheduleTime',(new moment()));
			break;
		case 'START_SCHEDULED_FLOW': 
			var newState = state.set('enableNext', true);
			newState = newState.setIn(['formData','endTimestamp'],null)
			return newState.setIn(['formData','conditionalScheduleType'],action.data);
			break;
		case 'CRON_EXPRESSION_VALID':
			return state.set('enableNext', true);
		case 'START_USER_ACTION_SELECTION_FLOW':
			var newState = state.set('UserInActionSelection', false);
			return newState.set('UserActionSelection', true);
			break;
		case 'START_USER_IN_ACTION_SELECTION_FLOW':
			var newState = state.set('UserActionSelection', false);
			return newState.set('UserInActionSelection', true);
			break;
		case 'START_NOTIFICATION_ON_FREQUENCY_FLOW':
			return state.setIn(['formData','conditionalScheduleType'],action.data);
			break;
		case 'START_ALL_DAY_NOTIFICATION_FLOW':
			var newState = state.set('NotificationOnFrequency', false);
			newState = newState.set('enableNext', true);
			return newState.set('AllDaysNotification', true);
			break;
		case 'REPEAT_FREQUENCY_CHANGE':
			var newState = state.set('RepeatEveryData', action.RepeatEveryData);
			newState = newState.set('RepeatType', action.RepeatType);
			newState = newState.set('RepeatEveryDataBypass',action.RepeatEveryDataBypass);
			return newState = newState.set('secondaryView', action.secondaryView);
			break;
		case 'REPEAT_EVERY_DATA_CHANGE':
			return state.set('RepeatEverySelectedData', action.data);
			break;
		case 'UPDATE_REPEAT_ON_WEEK_DAY_DATA':
			return state.set('RepeatOnWeekDayData',fromJS(action.data));
			break;
		case 'HANDLE_CHANGE_ON_ENDS_OCCURENCE_INPUT':
			return state.setIn(['formData','allowedOccurances'],action.data);
			break;
		case 'CHANGE_NOTIFICATIONS_ENDS':
			return state.set('EndNotificationOptions',fromJS(action.data));
			break;
		case 'CHANGE_REPEAT_BY_DAY_OF_MONTH_OR_WEEK_ENDS':
			return state.set('RepeatByDayOfMonthOrWeekData',fromJS(action.data));
			break;
		case 'SET_SCHEDULE_TIME':
			var newState = state.set('ScheduleTime',fromJS(action.data));
			newState = newState.setIn(['formData','startTimestamp'],action.data.unix());
			return newState;
			break;
		case 'EXTRACT_CRON_EXPRESSION':
			return state.setIn(['formData','schedule'],createCronExpression(state));
			break;
		case 'HANDLE_CHANGE_DAY_OF_WEEK':
			var cronExpression = state.get('formData').get('schedule').split(' ');
			cronExpression[5] = action.data.value+"#1";
			cronExpression[3] = '?';
			return state.setIn(['formData','schedule'],cronExpression.join(' '));
			break;
		case 'HANDLE_CHANGE_DAY_OF_MONTH':
			var cronExpression = state.get('formData').get('schedule').split(' ');
			cronExpression[3] = action.data.value;
			cronExpression[5] = '?';
			var newState = state.setIn(['formData','schedule'],cronExpression.join(' '));
			return newState.set('selectedDayOfMonth',action.data);
			break;
		case 'ENDS_ON_PARTICULAR_DATE':
			return state.setIn(['formData','endTimestamp'],parseInt(action.data.format('x')));
			break;
		case 'UPDATE_NOTIFICATION_DATA_WHEN':
			if(action.data.notificationEvent){
				if(!action.data.notificationEvent.eventType){
					action.data.notificationEvent.eventType = 'SCHEDULED';
				}
				if(!action.data.notificationEvent.eventUserType){
					action.data.notificationEvent.eventUserType = 'PILOT';
				}
				var newState = state.set('formData',fromJS(action.data.notificationEvent));
				return newState.set('draftSaved',true);
			}
			else{
				return state;
			}
			break;
		case 'DO_NOTHING':
			return state;
		default: 
			return state;
			break;
	}	
};