import React from "react";
import classNames from "classnames";
import { makeStyles } from "@material-ui/core/styles";

import Header from "components/Header/Header.js";
import HeaderLinks from "components/Header/HeaderHonda.js";
import Footer from "components/Footer/FooterHonda.js";
import Checkout from "pages-sections/yamaha/cart/checkout.js";
import Parallax from "components/Parallax/Parallax.js";
import styles from "assets/jss/nextjs-material-kit/pages/components.js";
import GetCheckoutproduct from "api/cart/checkout.js";
import Cookies from "cookies";

const useStyles = makeStyles(styles);
const ProductDetails = function ({ province, cities, backend, checkoutproduct, user, transactionToken, ...props })  {
    const classes = useStyles();
    const { ...rest } = props;
    return (
        <div>
        <Header
            rightLinks={<HeaderLinks username={user} />}
            fixed
            color="info"
            changeColorOnScroll={{
            height: 400,
            color: "white"
            }}
            {...rest}
        />
        <Parallax image={require("assets/img/Promotion_2-1.jpg")} width="200px"/>
        <div className={classNames(classes.main, classes.mainRaised)}>
            <Checkout province={province} cities={cities} checkoutproduct={checkoutproduct} transactionToken={transactionToken} backend={backend} />  
        </div>
        <Footer />
        </div>
    );
}

export default ProductDetails;

export async function getServerSideProps(context) {
    var {query} = context;
	var checkoutproduct = [];
    const backend = process.env.BACKEND_SERVER_URI;

    var { req, resp } = context;
    const cookies = new Cookies(req, resp);
    var user = "";
    var userObj = (await cookies.get("user"))
        ? JSON.parse(await cookies.get("user"))
        : null;
    if (userObj) {
        let sessionId = userObj["partners_login_states"].filter(function (i) {
        return (
            i.business_partner && i.business_partner.name.toUpperCase() == "YAMAHA"
        );
        });
        if (sessionId.length != 0) user = userObj["username"];
    }

	var res = await GetCheckoutproduct.GetCheckoutproduct(query.s||0);
	if (res["STATUS"] === 1) {
		checkoutproduct = res["DATA"]["products"];
	}

    //midtrans
    var parameters = await GetCheckoutproduct.GetCheckoutproductBayar(query.s||0);
    var transactionToken = [];
    if ( parameters["STATUS"] === 1 )
    {
        const midtransClient = require('midtrans-client');
        let snap = new midtransClient.Snap({
            isProduction : false,
            serverKey : 'SB-Mid-server-SfBhLkXXlTxCBx7EYP5T2k3d',
            clientKey : 'SB-Mid-client-srx674LjNbEybd4-'
        });
        let parameter = {
            "transaction_details": {
                "order_id":parameters["DATA"]["product"]["id"],
                "gross_amount":parameters["DATA"]["product"]["price"],
            }, "credit_card":{
                "secure" : true
            },
            "customer_details": {
                    "first_name": "Yusmardi",
                    "last_name": "anto",
                    "email": "yusmardianto@thamrin.co.id",
                    "phone": "087797315685",
                    "billing_address": 
                {
                    "first_name": "Yusmardi",
                    "last_name": "anto",
                    "email": "yusmardianto@thamrin.co.id",
                    "phone": "087797315685",
                    "address": "Thamrin Indrapura Jl.Aipda Karel Satsuit Tubun",
                    "city": "Kec.Ilir Tim.I, Palembang",
                    "postal_code": "30114",
                    "country_code": "IDN"
                },
                "shipping_address": 
                {
                    "first_name": "Yusmardi",
                    "last_name": "anto",
                    "email": "yusmardianto@thamrin.co.id",
                    "phone": "087797315685",
                    "address": "Thamrin Indrapura Jl.Aipda Karel Satsuit Tubun",
                    "city": "Kec.Ilir Tim.I, Palembang",
                    "postal_code": "30114",
                    "country_code": "IDN"
                }
            }
        };
        
        await snap.createTransaction(parameter)
            .then((transaction)=>{
                // transaction token
                transactionToken = transaction.token;
                console.log('transactionToken:',transactionToken);
        
                // transaction redirect url
                let transactionRedirectUrl = transaction.redirect_url;
                console.log('transactionRedirectUrl:',transactionRedirectUrl);
            })
            .catch((e)=>{
                console.log('Error occured:',e.message);
        });
    }
    
    //rajaOngkir
    var province = [];
    var cities = [];
    var RajaOngkir = require('rajaongkir-nodejs').Starter('f4ac703bb25ada32478d52ef2e1cab7a');

    await RajaOngkir.getProvinces().then(function (result){
        province = result;
    }).catch(function (error){
        // Aksi ketika error terjadi
    });

    await RajaOngkir.getCities().then(function (result){
        cities = result;
    }).catch(function (error){
        // Aksi ketika error terjadi
    });

	return {
		props: { province, cities, user, checkoutproduct, backend, transactionToken }, // will be passed to the page component as props
	};
}