import ActionType from './globalActionType';
import { Alert } from 'react-native';

const globalState = {

    //Set login di set ketika init
    email: '',
    password: '',

    //set register
    full_name: '',
    dob_day: '',
    dob_month: '',
    dob_year: '',
    gender: '',

    //Set device info di set ketika init
    fb_token: '',
    device_id: '',
    os_name: '',
    os_version: '',
    app_version: '',
    session_id: '',


    //set change_profile
    gender_display: '',

    //set registration
    validation_reg: false,

    registration_id: '',
    isEmailverif: false,
    //set position
    position: 'Home',
    pageEmailConfirmation: false,
    proses: '',

    language: 'id',
    set_card: false,
    URI: '',
    URI_IDCARD: '',
    id_card64: false,
    img64: false,
    selfie: false,
    idcard: false,

    BASE64_SELFIE: '',
    BASE64_ID: '',

    outlet_id: '',
    name_outlet: '',
    type_pickup: true,

    type_trans: '',

    quantity: 0,
    orders: 0,
    cart_shop: [],

    menu_item: [],

    order_item: [],
    order_quantity: 0,
    order_total: 0,

    address: '',
    addressId: '',

    grabtype: '',
    grabamount: 0,
    grabpickup: '',
    grabdropoff: '',
    grabdestination: '',

    notes:'',

    balanceUsed: '',
    pointused: '',

    trans_id: '',

    lat: '',
    long: '',

    voucher: [],
    value_voucher: '',
    home_address: '',
    outlet_detailadress: '',

    isSubmitResetPassword: false,
    BASE_URL:'https://excelsocrm.ravintoladev.com/'

}

const rootReducer = (state = globalState, action) => {
    switch (action.type) {
        case ActionType.SET_LOGIN_INFO: {
            return {
                ...state,
                email: action.data.email,
                password: action.data.password,
                session_id: action.data.session_id
            }
        }
        case ActionType.SET_EMAIL_VERIFICATION: {
            return {
                ...state,
                isEmailverif: action.data.isEmailverif,
            }
        }
        case ActionType.SET_CHANGE_RESET_PASSWORD: {
            return {
                ...state,
                isSubmitResetPassword: action.data.isSubmitResetPassword,
            }
        }
        case ActionType.SET_TYPE: {
            if (action.data.type_pickup) {
                delivery_amount = 0
            } else {
                delivery_amount = state.grabamount
            }

            return {
                ...state,
                type_pickup: action.data.type_pickup,
                grabamount: delivery_amount
            }
        }
        case ActionType.SET_GRAB: {
            return {
                ...state,
                // grabtype:  action.data.grabtype,
                grabamount: action.data.grabamount,
                // grabpickup: action.data.grabpickup,
                // grabdropoff: action.data.grabdropoff,
                // grabdestination: action.data.grabdestination,
            }
        }
        case ActionType.SET_ORDERS: {
            return {

                ...state,
                balanceUsed: action.data.balanceUsed,
                pointused: action.data.pointused,
            }
        }
        case ActionType.SET_PAGE: {
            return {
                ...state,
                pageEmailConfirmation: action.data.pageEmailConfirmation
            }
        }

        case ActionType.SET_TRANS_TYPE: {
            return {
                ...state,
                type_trans: action.data.type_trans
            }
        }

        case ActionType.SET_DEVICE_INFO: {
            return {
                ...state,

                fb_token: action.data.fb_token,
                device_id: action.data.device_id,
                os_name: action.data.os_name,
                os_version: action.data.os_version,
                app_version: action.data.app_version,
            }
        }

        case ActionType.SET_REGISTRATION: {
            return {
                ...state,
                full_name: action.data,
                dob_day: action.dob_day,
                dob_month: action.dob_month,
                dob_year: action.dob_year,
                gender: action.dob_year,
                email: action.data.email,
                validation_reg: action.data.validation_reg,
                registration_id: action.data.registration_id
            }
        }

        case ActionType.SET_CHANGE_LANGUAGE: {
            return {
                ...state,
                language: action.data.language,
            }
        }
        case ActionType.SET_CHANGE_PROFIL: {
            return {
                ...state,
                full_name: action.full_name,
                gender_display: action.gender_display
            }
        }
        case ActionType.SET_RESET_PASSWORD: {
            return {
                ...state,
                email: action.data.email,
            }
        }
        
        case ActionType.SET_PROSES: {
            return {
                ...state,
                proses: action.data.proses
            }
        }
        case ActionType.SET_CHANGE_EMAIL: {
            return {
                ...state,
                email: action.data.email,
            }
        }
        case ActionType.SET_BASE_URL: {
            return {
                ...state,
                BASE_URL: action.data.BASE_URL,
            }
        }
        case ActionType.SET_CHANGE_URI_SELFI: {
            return {
                ...state,
                URI: action.data.URI,
                BASE64_SELFIE: action.data.BASE64_SELFIE
                // id_card64:action.data.id_card64,
                // img64:action.data.img64

            }
        }

        case ActionType.SET_CHANGE_URI_ID: {
            return {
                ...state,
                URI_IDCARD: action.data.URI_IDCARD,
                BASE64_ID: action.data.BASE64_ID
                // id_card64:action.data.id_card64,
                // img64:action.data.img64

            }
        }

        case ActionType.SET_CHANGE_CAMERA: {
            return {
                ...state,
                selfie: action.data.selfie,
                idcard: false
            }
        }
        case ActionType.SET_CHANGE_IMAGE_ID: {
            return {
                ...state,
                idcard: action.data.idcard,
                selfie: false
            }
        }

        case ActionType.SET_VOUCHER: {
            return {
                ...state,
                voucher: action.data.voucher,
                value_voucher: action.data.value_voucher
            }
        }
        case ActionType.SET_CHANGE_IMAGE_SELFI: {
            return {
                ...state,
                selfie: action.data.selfie
            }
        }
        case ActionType.SET_CARD: {
            return {
                ...state,
                set_card: action.data.set_card

            }
        }
        case ActionType.SET_CORDINAT: {
            return {
                ...state,
                lat: action.data.lat,
                long: action.data.long

            }
        }
        case ActionType.SET_CHANGE_OUTLET: {
            return {
                ...state,
                outlet_id: action.data.outlet_id,
                name_outlet: action.data.name_outlet,
                outlet_detailadress: action.data.outlet_detailadress

            }
        }
        case ActionType.SET_CHANGE_SHOP: {
            return {
                ...state
            }
        }
        case ActionType.SET_ADDRESS: {
            return {
                ...state,
                address: action.data.address,
                addressId: action.data.addressId,
                home_address: action.data.home_address
            }
        }
        case ActionType.SET_TRANS_ID: {
            return {
                ...state,
                trans_id: action.data.trans_id
            }
        }
        case ActionType.SET_LOGOUT: {
            return {
                ...state,
                session_id: action.data.session_id,
            }
        }

        case ActionType.ADD_TO_CHART: {

            let addedItem = action.data.item
            let is_exist = state.order_item.find(item => addedItem.id == item.id)
            let order_item = []
            if (is_exist) {
                // update

                updated_data = []
                for (let i = 0; i < state.order_item.length; i++) {
                    const old_data = state.order_item[i];
                    const data = old_data;
                    if (old_data.id == addedItem.id) {
                        update = old_data
                        if (update.quantity == NaN) {
                            update.quantity = 1
                        }
                        update.quantity += 1
                        console.log('Update : ' + JSON.stringify(update))
                        data = { ...old_data, ...update }
                    }


                    updated_data.push(data)
                }
                order_item = updated_data
            } else {
                // add
                addedItem.quantity = 1
                console.log('Baru : ' + JSON.stringify(addedItem))
                order_item = [...state.order_item, addedItem]
            }

            let quantity = state.order_quantity + 1
            let total = parseInt(state.order_total) + parseInt(addedItem.price)


            let menu_item = []
            for (let i = 0; i < state.menu_item.length; i++) {
                const row = state.menu_item[i];

                if (row.id == addedItem.id) {
                    let is_exist = order_item.find(item => addedItem.id == item.id)
                    if (is_exist) {
                        row.qty = is_exist.quantity
                    }
                }

                menu_item.push(row)
            }

            return {
                ...state,
                menu_item: menu_item,
                order_item: order_item,
                order_quantity: quantity,
                order_total: total
            }
        }


        case ActionType.CHANGE_TO_CHART: {

            let addedItem = action.data.item
            let is_exist = state.order_item.find(item => addedItem.id == item.id)
            let order_item = []
            if (is_exist) {
                // update

                updated_data = []
                for (let i = 0; i < state.order_item.length; i++) {
                    const old_data = state.order_item[i];
                    const data = old_data;
                    if (old_data.id == addedItem.id) {
                        update = old_data
                        if (update.quantity == NaN) {
                            update.quantity = 1
                        }

                        console.log('Update : ' + JSON.stringify(update))
                        data = { ...old_data, ...update }
                    }


                    updated_data.push(data)
                }
                order_item = updated_data
            } else {
                // addcd ..
                order_item = [...state.order_item]
            }

            let quantity = state.order_quantity



            let menu_item = []
            for (let i = 0; i < state.menu_item.length; i++) {
                const row = state.menu_item[i];

                if (row.id == addedItem.id) {
                    let is_exist = order_item.find(item => addedItem.id == item.id)
                    if (is_exist) {
                        row.qty = is_exist.quantity
                    }
                }

                menu_item.push(row)
            }

            return {
                ...state,
                menu_item: menu_item,
                order_item: order_item,
                order_quantity: quantity,
            }
        }

        case ActionType.REDUCE_QUANTITY_ITEM: {

            let addedItem = action.data.item
            let is_exist = state.order_item.find(item => addedItem.id == item.id)
            let order_item = []
            if (is_exist) {
                // update

                updated_data = []
                for (let i = 0; i < state.order_item.length; i++) {
                    const old_data = state.order_item[i];
                    const data = old_data;
                    if (old_data.id == addedItem.id) {
                        update = old_data
                        if (update.quantity == NaN) {
                            update.quantity = 1
                        }

                        if (update.quantity == 0) {

                            update.quantity = 0

                        } else {
                            if (update.quantity - 1 == 0) {
                                data = null
                            } else {
                                update.quantity -= 1
                                console.log('Update : ' + JSON.stringify(update))
                                data = { ...old_data, ...update }
                            }
                        }

                    }

                    if (data != null) {
                        updated_data.push(data)
                    }
                }
                order_item = updated_data
                // } else {
                //     // add
                //     addedItem.quantity = 1

                //     console.log('Baru : ' + JSON.stringify(addedItem))
                //     order_item = [...state.order_item, addedItem]
            }

            // if (state.order_quantity === 0 && state.order_total === 0) {

            //     state.order_quantity = 0
            //     state.order_total = 0

            //     console.log("MASUK INI")
            // }
            let quantity = state.order_quantity - 1
            let total = parseInt(state.order_total) - parseInt(addedItem.price)

            let menu_item = []
            for (let i = 0; i < state.menu_item.length; i++) {
                const row = state.menu_item[i];

                if (row.id == addedItem.id) {
                    let is_exist = order_item.find(item => addedItem.id == item.id)
                    if (is_exist) {
                        row.qty = is_exist.quantity
                    } else {
                        row.qty = 0
                    }
                }

                menu_item.push(row)
            }

            return {
                ...state,
                menu_item: menu_item,
                order_item: order_item,
                order_quantity: quantity,
                order_total: total
            }

        }

        case ActionType.REMOVE_FROM_CHART: {

            let addedItem = action.data.item
            let is_exist = state.order_item.find(item => addedItem.id == item.id)
            let new_items = state.order_item.filter(item => addedItem.id !== item.id)
            let order_item = []
            if (is_exist) {
                // update

                updated_data = []
                for (let i = 0; i < state.order_item.length; i++) {
                    const old_data = state.order_item[i];
                    const data = old_data;
                    if (old_data.id != addedItem.id) {
                        updated_data.push(data)
                        quantity += data.quantity
                        total += (data.quantity * data.price)
                    }
                }

                order_item = updated_data
                let quantity = state.order_quantity
                let total = parseInt(state.order_total) - parseInt(addedItem.price)

                console.log("UPDATE " + order_item)
            }

            return {
                ...state,
                order_item: new_items,
            }
        }
        case ActionType.SET_RECALCULATE: {
            return {
                ...state,
                order_total: action.data.order_total,
                order_quantity: action.data.order_quantity,
                order_item: action.data.order_item

            }
        }

        case ActionType.SET_REEDEM: {
            return {
                ...state,
                in_payment: action.data.in_payment, 
                redeem_code :action.data.redeem_code, 
                balance_redeem : action.data.balance_redeem, 
                point_redeem:action.data.point_redeem

            }
        }

        case ActionType.SET_ORDER_FINISH: {
            return {
                ...state,
                type_pickup: true,
                order_total: 0,
                order_quantity: 0,
                order_item: [],
                grabamount: 0,
                outlet_id: '',
                name_outlet: '',
                address_id: '',
                voucher: [],
                value_voucher: ''

            }
        }
        case ActionType.REMOVE_VOUCHER: {
            return {
                ...state,
                voucher: [],
                value_voucher: ''
            }
        }

        case ActionType.UPDATE_MENU: {
            const menu = action.data.menu;
            let total = 0
            let quantity = 0
            let list_menu = []
            let list_item = []


            for (let i = 0; i < state.order_item.length; i++) {
                const row = state.order_item[i];

                let is_updated = menu.find(item => item.id == row.id)

                // Update Price in Cart
                if (is_updated) {
                    row.price = parseInt(is_updated.price)
                }

                quantity += parseInt(row.quantity)
                total += parseInt(row.price) * parseInt(row.quantity)

                list_item.push(row)
            }

            let last_category = ''
            for (let i = 0; i < menu.length; i++) {
                const row = menu[i];
                // cari sudah ada belum di redux
                let is_xist = list_item.find(item => row.id == item.id)
                if (is_xist) {
                    row['qty'] = is_xist.quantity
                    row['note'] = is_xist.note
                } else {
                    row['qty'] = 0
                    row['note'] = ''
                }

                if (last_category != row.category.name) {
                    let category = {
                        "id": row.category.id,
                        "name": row.category.name,
                        "code": "CATEGORY"
                    }
                    list_menu.push(category)
                    list_menu.push(row)
                    last_category = row.category.name
                } else {
                    list_menu.push(row)
                }
            }

            return {
                ...state,
                menu_item: list_menu,
                order_total: total,
                order_quantity: quantity,
                order_item: list_item,

            }
        }

        case ActionType.CHANGE_QUANTITY: {
            const item = action.data.item;
            const new_quantity = action.data.new_quantity;
            let total = 0
            let quantity = 0
            let list_menu = []
            let list_item = []

            if (!isNaN(parseInt(new_quantity))) {
                console.log('Number : ' + parseInt(new_quantity))

                exist = false
                for (let i = 0; i < state.order_item.length; i++) {
                    const row = state.order_item[i];

                    if (row.id == item.id) {
                        // Update Price in Cart
                        row.quantity = parseInt(new_quantity)
                        exist = true
                    }

                    if (row.quantity > 0) {
                        quantity += parseInt(row.quantity)
                        total += parseInt(row.price) * parseInt(row.quantity)
                        list_item.push(row)
                    }
                }

                // kalo belum ada
                if (!exist) {
                    item.quantity = parseInt(new_quantity)
                    if (item.quantity < 0) {
                        item.quantity = 0
                    }
                    console.log('sama sekali blm ada : ' + JSON.stringify(item))
                    if (item.quantity > 0) {
                        quantity += parseInt(item.quantity)
                        total += parseInt(item.price) * parseInt(item.quantity)
                        list_item.push(item)
                    }
                }

                for (let i = 0; i < state.menu_item.length; i++) {
                    const row = state.menu_item[i];
                    // cari sudah ada belum di redux
                    let is_xist = list_item.find(it => it.id == row.id)
                    if (is_xist) {
                        row['qty'] = is_xist.quantity
                    } else {
                        console.log(parseInt(new_quantity))
                        if (parseInt(new_quantity) < 0) {
                            row.qty = 0
                        } else {
                            row.qty = 0
                        }
                    }

                    list_menu.push(row)
                }
                return {
                    ...state,
                    menu_item: list_menu,
                    order_total: total,
                    order_quantity: quantity,
                    order_item: list_item,
                }
            }

        }

        case ActionType.SET_EDIT_NOTE: {
            const update = action.data.item;
            // const menu = action.data.item
            // console.log("INI HASILNY"+ menu)

            // Update shopping chart pakai cara 1
            updated_data = []
            for (let i = 0; i < state.order_item.length; i++) {
                const old_data = state.order_item[i];
                const data = old_data;

                // dicari dulu object mana yg mau diupdate
                if (old_data.id == update.id) {
                    // kalo ketemu update data notenya
                    data.note = update.note
                    updated_data.push(data)
                } else {
                    // kalo bukan biarin pakai yg lama
                    updated_data.push(data)
                }
            }

            // Update menu list pakai cara 2
            updated_menu = state.menu_item
            
            // dicari dulu index keberapa yg mau diupdate notenya
            update_index = state.menu_item.findIndex((obj => obj.id == update.id));

            // update note
            updated_menu[update_index].note = update.note

            // console.log('update order_item', updated_data                                                                                                                                           );
            // console.log('update menu_item', updated_menu);

            return {
                ...state,
                order_item: updated_data,
                menu_item: updated_menu,
            }

        }

        default:
            return state;
    }
}

export default rootReducer;
