package kls.bookcan;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Shreesha K L on 23/01/2017.
 */

public class main_order extends Fragment
{
    main_order_inter objListener;
    public interface main_order_inter
    {
        public void orderRefresh();
    }
    @Override
    public void onAttach(Context context)
    {
        super.onAttach(context);
        try
        {
            objListener=(main_order_inter)context;
        }
        catch (ClassCastException ce)
        {

        }

    }
    int ordnum=1;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {

        //return super.onCreateView(inflater, container, savedInstanceState);
        final View view=inflater.inflate(R.layout.main_order,container,false);
        Button bt=(Button)view.findViewById(R.id.button_order);
        Spinner sp=(Spinner)view.findViewById(R.id.spinner12);
       // ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(view.getContext(),R.array.ordr_number,android.R.layout.simple_spinner_item);
        //adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //sp.setAdapter(adapter);
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
        {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
            {
                ordnum=Integer.parseInt(parent.getItemAtPosition(position).toString());

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent)
            {

            }
        });
        bt.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                new AlertDialog.Builder(view.getContext())
                        .setTitle("Conform")
                        .setMessage("Submit order?")
                        .setNegativeButton("Cancel", null)
                        .setPositiveButton("Order", new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface arg0, int arg1)
                            {
                                new OrderTask(view.getContext()).execute();
                            }
                        }).create().show();


            }
        });
        return view;
    }
    private class OrderTask extends AsyncTask<String, Integer, String>
    {
        String result="0";
        private Context context;
        public OrderTask(Context context)
        {
            this.context = context;
        }
        @Override
        protected String doInBackground(String... strs)
        {
            SharedPreferences sharedPref = context.getSharedPreferences("Implement here", Context.MODE_PRIVATE);
            String id=sharedPref.getString("id","No value");
            String ownid=sharedPref.getString("ownid","No value");
            if(id.equals("No value"))
            {
                result="notreg";
                return null;
            }
            if(ownid.equals("No value"))
            {
                result="noown";
                return null;
            }

            InputStream is = null;

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("quantity", ""+ordnum));

            nameValuePairs.add(new BasicNameValuePair("id", id.trim()));
            try{
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(new ip().getIP()+"Implement here");
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse response = httpClient.execute(httpPost);

                HttpEntity entity = response.getEntity();

                is = entity.getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                result = sb.toString();
            }
            catch (ClientProtocolException e)
            {
                result=e.getMessage();
                return null;
            }
            catch (IOException e)
            {
                result=e.getMessage();
                return null;
            }


            return null;
        }


        @Override
        protected void onPostExecute(String r)
        {
            if(result.trim().equals("1"))
            {
                Toast.makeText(context,"Order Successfull",Toast.LENGTH_LONG).show();
                objListener.orderRefresh();
            }
            else if (result.equals("notreg"))
            {
                Toast.makeText(context,"Please Signup",Toast.LENGTH_LONG).show();
            }
            else
            if (result.equals("noown"))
            {
                Toast.makeText(context,"Register to supplier",Toast.LENGTH_LONG).show();
            }
            else
                Toast.makeText(context,result,Toast.LENGTH_LONG).show();
        }
    }
}
