import axios from "axios";
import { fetchAnswerFailure } from "../actions/answer";
import setAuthorizationHeader from "./setAuthorizationHeader";
import Router from 'next/router';
//axios.defaults.headers.common = { 'X-Requested-With': 'XMLHttpRequest' }
axios.defaults.baseURL = (process.env.NODE_ENV !== 'production') ?
    'http://localhost/app_dev.php/' :
    process.env.SERVER_URL;

axios.interceptors.response.use(response => {
    return response;
}, error => {
    if (error.response.status === 401) {
        localStorage.setItem('ttJWT', '');
        console.log("REPONSE REDIRECT LOGIN")
        Router.push("/Login");
    }
    return error;
});

export default {
    user: {
        login: credentials =>
            axios.post("/api/login_check", { username: credentials.email, password: credentials.password }).then(res => res.data),
        loginOauth: ({ token, type }) =>
            axios.post("/api/login_check_oauth", { 'oauth-token': token, 'oauth-type': type }),
        fetchUser: () => {
            return axios.get("/api/user").then(res => { return res.data })
        },
        subscribeToNewsletter: (data) => {
            return axios.post(process.env.FRONT_SERVER + "/NewsletterSubscription", data).then(res => { return res })
        },
        register: (payload) => {
            return axios.post("/api/register", payload).then(res => res)
        },
        sendconfirmationEmail: (data) => {
            return axios.post(process.env.FRONT_SERVER + "/sendConfirmationEmail", data).then(res => { return res })
        },
        confirmUserAccount: (payload) => {
            return axios.post("/api/confirmAccount", payload).then(res => res)
        },
        updateUser: (payload) => {
            return axios.post("/api/update_user", payload, {
                headers: {
                    'Content-Type': `multipart/form-data;`
                },
                withCredentials: true
            }).then(res => res)
        },
        resetPassword: (payload) => {
            return axios.post("/api/reset_password", payload).then(res => res)
        },
        subscribeUserToPush: (payload) => {
            setAuthorizationHeader(localStorage.ttJWT)
            return axios.post("/api/userSubscriptionToPush", payload).then(res => res)
        },
        fetchUserSubscriptionToPush: () => {
            setAuthorizationHeader(localStorage.ttJWT)
            return axios.get(`/api/userSubscriptionToPush`).then(res => res)
        },
        uploadPicture: (payload) => {
            return axios.post("/api/update_profile_picture", payload, {
                headers: {
                    'Content-Type': `multipart/form-data;`
                },
                withCredentials: true
            }).then(res => res)
        },
    },
    ads: {
        fetchJob: (id) => {
            return axios.get(`api/jobs/${id}`).then(res => res.data)
        },

        //offset is the index position of the first element to start requesting at 
        // use 0|1 for isPromoted
        fetchJobs: ({ limit = null, order = "", keyword = "", offset = 1, status = 'PUBLISHED', isPromoted = false, isEmphasis = false }) => {
            isPromoted = isPromoted !== null ? isPromoted * 1 : isPromoted;
            isEmphasis = isEmphasis !== null ? isEmphasis * 1 : isEmphasis;

            return axios.get('api/jobs', { params: { offset, limit, order, keyword, status, isPromoted, isEmphasis } })
                .then(res => res.data)
        }

    },
    companies: {
        fetchCompany: id =>
            axios.get(`api/companies/${id}`).then(res => res.data),

        fetchCompanies: ({ limit = null, order = "", keyword = "", offset = 1, isEmphasis = null }) => {

            isEmphasis = isEmphasis !== null ? isEmphasis * 1 : isEmphasis;
            return axios.get('api/companies', { params: { offset, limit, order, keyword, isEmphasis } }).then(res => res.data);
        }
    },
    answers: {
        postAnswer: (payload) => {
            return axios.post("/api/answers", { adId: payload.adId, mediaId: payload.mediaId, companyId: payload.companyId }).then(res => res)
        },
        fetchJobsAnswered: ({ limit = null, order = "", keyword = "", offset = 1 }) => {
            return axios.get(`api/answers`, { params: { offset, limit, order, keyword } }).then(res => res.data)
        },
        fetchAnswer: (payload) => {
            setAuthorizationHeader(localStorage.ttJWT)
            return axios.get(`api/answers/${payload}`).then(res => res.data)
        },
        postMessage: (payload) => {
            return axios.post("/api/answers/message", { answerId: payload.answerId, message: payload.message }).then(res => res)
        },
        fetchAnswerMessages: (payload) => {
            setAuthorizationHeader(localStorage.ttJWT)
            return axios.get(`api/answers/${payload}/messages`).then(res => res.data)
        },
    },
    medias: {
        uploadMedia: (payload) => {
            return axios.post("/api/media", payload, {
                headers: {
                    'Content-Type': `multipart/form-data;`
                },
                withCredentials: true
            }).then(res => res)
        },
        uploadMediaPres: (payload) => {
            return axios.post("/api/mediaPres", payload, {
                headers: {
                    'Content-Type': `multipart/form-data;`
                },
                withCredentials: true
            }).then(res => res)
        },
        
    },
    cv:{
        uploadMediaCv: (payload) => {
            return axios.post("/api/mediaCv", payload, {
                headers: {
                    'Content-Type': `multipart/form-data;`
                },
                withCredentials: true
            }).then(res => res)
        }
    },
    stats: {
        countAdView: id => {
            if (!!localStorage.ttJWT)
                setAuthorizationHeader(localStorage.ttJWT)
                let continuerAds = true;
            
                if (sessionStorage.getItem("ads"+id)){
                    continuerAds=false;
                }
             
                if( continuerAds){
                    axios.get(`api/adAjaxRecStat/${id}`)
                    sessionStorage.setItem('ads'+id, id);
                }
        },
        countCompanyView: id => {
            if (!!localStorage.ttJWT){
                setAuthorizationHeader(localStorage.ttJWT);
            }

            let continuer = true;
            
            if (sessionStorage.getItem("companies"+id)){
                continuer=false;
            }
         
            if( continuer){
                axios.get(`api/companyAjaxRecStat/${id}`);
                sessionStorage.setItem('companies'+id, id);
            }
        }, 
    }


};