import ACTION from "../actions/actiontsTypes";
import {put, call} from 'redux-saga/effects';
import {goodsAttributesTypes} from "../constants/goods";
import {
    getAllOrders,
    deleteOrderByAdmin,
    appendOrderByAdmin,
    updateOrderByAdmin,
    deletePictureInGoodsAttributes,
    appendPictureInGoodsAttribute,
    updateGoods,
    deleteGoods,
    updateGoodsAttributes,
    deleteGoodsAttributes,
    getOrdersBySearchString
} from "../api/rest/restContoller";
import {brands, countryFragrance, genders, groups} from "../constants/goods";
import {createGoodsErrors} from "../constants/errors/goods";
import { toast } from 'react-toastify';
const CryptoJS = require("crypto-js");

export function* getAllOrdersForAdmin({ offset, searchString }) {
    // yield put({type: ACTION.ADMIN_ORDERS_REQUEST, numberPage: offset === 0 ? 0 : offset / 10});
    //
    // const values = {
    //   offset,
    //   searchString
    // };
    //
    // let encrypted = CryptoJS.AES.encrypt(
    //     JSON.stringify(values),
    //     window.localStorage.getItem("adminPrivateKey")
    // );
    // encrypted = encrypted.toString();
    //
    // try {
    //     const {data} = yield call(
    //         getAllOrders,
    //         encrypted,
    //         window.localStorage.getItem('token'),
    //     );
    //
    //     yield put({
    //         type: ACTION.ADMIN_ORDERS_RESPONSE,
    //         data: data
    //     })
    // }catch (e) {
    //     yield put({type: ACTION.ADMIN_ORDERS_ERROR, error: e});
    // }
}

export function* getOrdersBySearchStrings({ searchString }) {
    yield put({type: ACTION.ADMIN_ORDERS_REQUEST, numberPage: 0});

    try {
        const {data} = yield call(
            getOrdersBySearchString,
            window.localStorage.getItem('token'),
            searchString,
            CryptoJS.AES.encrypt(
                JSON.stringify({}),
                window.localStorage.getItem("adminPrivateKey")
            )
        );

        yield put({
            type: ACTION.ADMIN_ORDERS_RESPONSE,
            data: data
        })
    }catch (e) {
        yield put({type: ACTION.ADMIN_ORDERS_ERROR, error: e});
    }
}

export function* deleteOrdersAdmin({ orderId }) {
    yield put({type: ACTION.ADMIN_ORDERS_REQUEST});

    try {
        const {data} = yield call(
            deleteOrderByAdmin,
            orderId,
            window.localStorage.getItem('token'),
            CryptoJS.AES.encrypt(
                JSON.stringify({}),
                window.localStorage.getItem("adminPrivateKey")
            )
        );

        yield put({
            type: ACTION.ADMIN_ORDERS_RESPONSE,
            data: data
        })
    }catch (e) {
        yield put({type: ACTION.ADMIN_ORDERS_ERROR, error: e});
    }
}

export function* appendOrdersAdmin ({ packId, goodId }) {
    yield put({type: ACTION.ADMIN_ORDERS_REQUEST});

    const values = {
      packId: packId,
      goodId: goodId
    };
    let encrypted = CryptoJS.AES.encrypt(
        JSON.stringify(values),
        window.localStorage.getItem("adminPrivateKey")
    );
    encrypted = encrypted.toString();
    try {
        const {data} = yield call(
            appendOrderByAdmin,
            encrypted,
            window.localStorage.getItem('token')
        );

        yield put({
            type: ACTION.ADMIN_ORDERS_RESPONSE,
            data: data
        })
    }catch (e) {
        yield put({type: ACTION.ADMIN_ORDERS_ERROR, error: e});
    }
}

export function* updateOrderAdmin({ ordersIdsArray, dataForUpdate }) {
    yield put({type: ACTION.ADMIN_ORDERS_REQUEST});

    const values = {
        orderId: ordersIdsArray,
        dataForUpdate: dataForUpdate
    };
    let encrypted = CryptoJS.AES.encrypt(
        JSON.stringify(values),
        window.localStorage.getItem("adminPrivateKey")
    );

    encrypted = encrypted.toString();
    try {
        const {data} = yield call(
            updateOrderByAdmin,
            encrypted,
            window.localStorage.getItem('token')
        );

        yield put({
            type: ACTION.ADMIN_ORDERS_RESPONSE,
            data: data
        })
    }catch (e) {
        yield put({type: ACTION.ADMIN_ORDERS_ERROR, error: e});
    }
}


export function* adminUpdateGoods({ goodsData }) {


    Object.assign(goodsData, {
        goodsBrandId: +brands[goodsData.goodsBrandId] || goodsData.goodsBrandId || Object.values(brands)[0],
        goodsGroupId: +groups[goodsData.goodsGroupId] || goodsData.goodsGroupId || Object.values(groups)[0],
        goodsGender: genders[goodsData.goodsGender] || goodsData.goodsGender || Object.values(genders)[0],
        goodsMadeIn: countryFragrance[goodsData.goodsMadeIn]
            || goodsData.goodsMadeIn || Object.values(countryFragrance)[0]
    });

    const values = {
        goodsData: goodsData
    };
    let encrypted = CryptoJS.AES.encrypt(
        JSON.stringify(values),
        window.localStorage.getItem("adminPrivateKey")
    );

    encrypted = encrypted.toString();



    yield put({type: ACTION.ADMIN_GOODS_REQUEST});


    try {
        const {data} = yield call(
            updateGoods,
            encrypted,
            window.localStorage.getItem('token')
        );

        yield toast.success("Товар создан");

        yield put({
            type: ACTION.ADMIN_GOODS_RESPONSE,
            data: data
        })
    }catch (e) {
        yield put({type: ACTION.ADMIN_GOODS_ERROR, error: e});
        yield toast.error(createGoodsErrors[e.response.data.status]);
    }
}

export function* adminDeleteGoods({ idSingleGoods, dynamicSearchData }) {

    let encrypted = CryptoJS.AES.encrypt(
        JSON.stringify({}),
        window.localStorage.getItem("adminPrivateKey")
    );

    encrypted = encrypted.toString();


    yield put({type: ACTION.ADMIN_GOODS_REQUEST});


    try {
        const {data} = yield call(
            deleteGoods,
            idSingleGoods,
            encrypted,
            window.localStorage.getItem('token')
        );

        yield put({
            type: ACTION.ADMIN_GOODS_RESPONSE,
            data: data
        });
        yield put({
            type: ACTION.DYNAMIC_SEARCH_GOODS_RESPONSE,
            data: dynamicSearchData.filter((elem) => elem.id != idSingleGoods)
        });
        yield toast.success("Товар удален");
    }catch (e) {
        yield put({type: ACTION.ADMIN_GOODS_ERROR, error: e});
        yield toast.error("Что-то пошло не так. Товар не удален.")
    }
}

export function* appendPictureInAttribute({ formData, idAttribute }) {


    const values = {
        idAttribute: idAttribute
    };
    let encrypted = CryptoJS.AES.encrypt(
        JSON.stringify(values),
        window.localStorage.getItem("adminPrivateKey")
    );

    encrypted = encrypted.toString();


    yield put({type: ACTION.ADMIN_GOODS_REQUEST});


    try {
        const {data} = yield call(
            appendPictureInGoodsAttribute,
            formData,
            encrypted,
            localStorage.getItem('token')
        );


        yield put({
            type: ACTION.ADMIN_GOODS_RESPONSE,
            data: data
        })
    }catch (e) {
        yield put({type: ACTION.ADMIN_GOODS_ERROR, error: e});
    }
}

export function* deletePictureInGoodsAttribute({ goodsAttributesId, pictureName }) {

    yield put({type: ACTION.ADMIN_GOODS_REQUEST});

    const values = {
        goodsAttributesId: goodsAttributesId,
        pictureName: pictureName
    };
    let encrypted = CryptoJS.AES.encrypt(
        JSON.stringify(values),
        window.localStorage.getItem("adminPrivateKey")
    );
    encrypted = encrypted.toString();
    try {
        const {data} = yield call(
            deletePictureInGoodsAttributes,
            encrypted,
            window.localStorage.getItem('token')
        );

        yield put({
            type: ACTION.ADMIN_GOODS_RESPONSE,
            data: data
        })
    }catch (e) {
        yield put({type: ACTION.ADMIN_GOODS_ERROR, error: e});
    }
}

export function* updateGoodsAttribute({goodsAttributesData, goodsId, goodsAttributeId}) {

    yield put({type: ACTION.ADMIN_GOODS_REQUEST});

    Object.assign(goodsAttributesData, {
       nameAttribute: goodsAttributesTypes[goodsAttributesData.nameAttribute]
           || Object.values(goodsAttributesTypes)[0]
    });

    const values = {
        goodsAttributesData: goodsAttributesData,
        goodsId: goodsId,
        goodsAttributeId: goodsAttributeId
    };
    let encrypted = CryptoJS.AES.encrypt(
        JSON.stringify(values),
        window.localStorage.getItem("adminPrivateKey")
    );
    encrypted = encrypted.toString();

    try {
        const {data} = yield call(
            updateGoodsAttributes,
            encrypted,
            window.localStorage.getItem('token')
        );

        yield put({
            type: ACTION.ADMIN_GOODS_RESPONSE,
            data: data
        })
    }catch (e) {
        yield put({type: ACTION.ADMIN_GOODS_ERROR, error: e});
    }
}

export function* goodsAttributesDelete({goodsAttributesId}) {
    yield put({type: ACTION.ADMIN_GOODS_REQUEST});

    let encrypted = CryptoJS.AES.encrypt(
        JSON.stringify({}),
        window.localStorage.getItem("adminPrivateKey")
    );
    encrypted = encrypted.toString();

    try {
        const {data} = yield call(
            deleteGoodsAttributes,
            goodsAttributesId,
            encrypted,
            window.localStorage.getItem('token')
        );

        yield put({
            type: ACTION.ADMIN_GOODS_RESPONSE,
            data: data
        })
    }catch (e) {
        yield put({type: ACTION.ADMIN_GOODS_ERROR, error: e});
    }
}

