package com.example.mhwong.nctulibrary;

import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.pnikosis.materialishprogress.ProgressWheel;

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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class BorrowListActivity extends ActionBarActivity{
    String keyword;
    final static String BORROWURL = "https://library-mhwong2007.rhcloud.com/api/borrow/list/";
    private RecyclerView searchResultRecycleView;
    private RecyclerView.LayoutManager searchResultRecyclerViewLayoutManager;
    private ProgressWheel progressBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result_list);

        progressBar = (ProgressWheel)findViewById(R.id.progressBarInSearchResultList);

        Intent intent = getIntent();
        String keyword = intent.getStringExtra("keyword");

        searchResultRecycleView = (RecyclerView) findViewById(R.id.searcResultRecycleView);
        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        searchResultRecycleView.setHasFixedSize(true);

        // use a linear layout manager
        searchResultRecyclerViewLayoutManager = new LinearLayoutManager(this);
        searchResultRecycleView.setLayoutManager(searchResultRecyclerViewLayoutManager);
        new SearchTask(keyword).execute();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.search_result_list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //Create a AsynTask to perform searching
    class SearchTask extends AsyncTask<String, Void, Void>
    {
        String keyword;
        SearchResultRecyclerViewAdapter searchResultRecyclerViewAdapter;
        ArrayList<Item> items;

        public SearchTask(String keyword){
            this.keyword = keyword;
        }

        @Override
        protected void onPreExecute(){
            progressBar.spin();
        }

        // value returned by doInBackground will be passed to onPostExecute
        @Override
        protected Void doInBackground(String... arg0){
            Connection connection = null;

            try {

                HttpPost httpPost;
                List<NameValuePair> nameValuePairs = new ArrayList<>();

                // connect to login endpoint
                DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
                httpPost = new HttpPost(BORROWURL);

                // search parameter
                nameValuePairs.add(new BasicNameValuePair("id", DataHolder.getInstance().getUserID()));
                nameValuePairs.add(new BasicNameValuePair("token", DataHolder.getInstance().getToken()));
                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                // execute http post
                HttpResponse response = defaultHttpClient.execute(httpPost);

                // return items
                items = new ArrayList<Item>();

                if(response.getStatusLine().getStatusCode() == 200) { // search has result
                    HttpEntity httpEntity = response.getEntity();
                    // read json string
                    InputStream inputStream = httpEntity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    String result = reader.readLine();

                    // build json array
                    JSONArray jsonArray = new JSONArray(result);
                    for(int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);

                        Item item = new Item();
                        item.setBook(jsonObject.getString("name"));
                        item.setAuthor(jsonObject.getString("author"));
                        item.setISBN(jsonObject.getString("ISBN"));
                        item.setYear(jsonObject.getString("year"));
                        item.setPublisher(jsonObject.getString("publisher"));
                        item.setVersion(jsonObject.getString("version"));
                        item.setLocation(jsonObject.getString("location"));
                        item.setSize(jsonObject.getString("size"));
                        item.setBookNumber(jsonObject.getString("bookNumber"));
                        item.setLibrarycode(jsonObject.getString("librarycode"));
                        items.add(item);
                    }
                }
                searchResultRecyclerViewAdapter = new SearchResultRecyclerViewAdapter(items, BorrowListActivity.this);

            } catch (JSONException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        //therefore we will update TextView result here
        @Override
        protected void onPostExecute(Void params){
            super.onPostExecute(params);
            progressBar.stopSpinning();

            searchResultRecycleView.setAdapter(searchResultRecyclerViewAdapter);
            if (items.size() == 0) {
                NotificationDialogFragment dialogFragment = NotificationDialogFragment.newInstance("您沒有借過任何書籍");
                dialogFragment.show(getSupportFragmentManager(),"NoResult");
            }
        }
    }

    //inner class an data structure to store tag and value
    class Item {
        private String book;
        private String author;
        private String ISBN;
        private String year;
        private String bookNumber;
        private String format;
        private String location;
        private String version;
        private String publisher;
        private String size;
        private String librarycode;

        public Item() {
            this("","","","","","","","","","","");
        }
        public Item(String book, String author, String ISBN, String year, String bookNumber, String format, String location, String version, String publisher, String size, String librarycode){
            super();
            setBook(book);
            setAuthor(author);
            setISBN(ISBN);
            setYear(year);
            setBookNumber(bookNumber);
            setFormat(format);
            setLocation(location);
            setVersion(version);
            setPublisher(publisher);
            setSize(size);
            setLibrarycode(librarycode);
        }

        public void setBook(String book){
            this.book = book;
        }

        public void setAuthor(String author){
            this.author = author;
        }
        public void setISBN(String ISBN) {
            this.ISBN = ISBN;
        }
        public void setYear(String year) {
            this.year = year;
        }
        public void setBookNumber(String bookNumber) {
            this.bookNumber = bookNumber;
        }
        public void setFormat(String format) {
            this.format = format;
        }
        public void setLocation(String location) {
            this.location = location;
        }
        public void setVersion(String version) {
            this.version = version;
        }
        public void setPublisher(String publisher) {
            this.publisher = publisher;
        }
        public void setSize(String size) {
            this.size = size;
        }
        public void setLibrarycode(String librarycode) {
            this.librarycode = librarycode;
        }
        public String getBook(){
            return book;
        }
        public String getAuthor(){
            return author;
        }
        public String getISBN() {
            return ISBN;
        }
        public String getYear() {
            return year;
        }
        public String getBookNumber() {
            return bookNumber;
        }
        public String getFormat() {
            return format;
        }
        public String getLocation() {
            return location;
        }
        public String getVersion() {
            return  version;
        }
        public String getPublisher() {
            return publisher;
        }
        public String getSize() {
            return size;
        }
        public String getLibrarycode() {
            return librarycode;
        }
    }


    //inner class to override adapter
    class SearchResultRecyclerViewAdapter extends RecyclerView.Adapter<SearchResultRecyclerViewAdapter.ViewHolder> {

        private final ArrayList<Item> searchResultArrayList;
        private Context context;
        // Allows to remember the last item shown on screen, for animation
        private int lastPosition = -1;

        //provide a reference to the views for each data item
        public class ViewHolder extends RecyclerView.ViewHolder{
            public View view;
            RelativeLayout container;
            public ViewHolder(View view) {
                super(view);
                this.view = view;
                container = (RelativeLayout)view.findViewById(R.id.relativeLayoutInSearchResultRow);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = getPosition();
                        Intent intent = new Intent(BorrowListActivity.this, SearchResult.class);

                        intent.putExtra("book", searchResultArrayList.get(position).getBook());
                        intent.putExtra("author", searchResultArrayList.get(position).getAuthor());
                        intent.putExtra("ISBN", searchResultArrayList.get(position).getISBN());
                        intent.putExtra("year", searchResultArrayList.get(position).getYear());
                        intent.putExtra("publisher", searchResultArrayList.get(position).getPublisher());
                        intent.putExtra("version", searchResultArrayList.get(position).getVersion());
                        intent.putExtra("location", searchResultArrayList.get(position).getLocation());
                        intent.putExtra("size", searchResultArrayList.get(position).getSize());
                        intent.putExtra("bookNumber", searchResultArrayList.get(position).getBookNumber());
                        intent.putExtra("librarycode", searchResultArrayList.get(position).getLibrarycode());

                        startActivity(intent);
                    }
                });
            }
        }

        public SearchResultRecyclerViewAdapter (ArrayList<Item> searchResultArrayList, Context context) {
            this.searchResultArrayList = searchResultArrayList;
            this.context = context;
        }

        @Override
        public SearchResultRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.search_result_row, viewGroup, false);
            ViewHolder viewHolder = new ViewHolder(view);

            return viewHolder;

        }

        //Replace the content of a view
        @Override
        public void onBindViewHolder(SearchResultRecyclerViewAdapter.ViewHolder viewHolder, int position) {
            TextView bookNameInSearchResult = (TextView) viewHolder.view.findViewById(R.id.bookNameInSearchResult);
            TextView ISBNInSearchResult = (TextView) viewHolder.view.findViewById(R.id.ISBNInSearchResult);
            TextView publishYearInSearchResult = (TextView) viewHolder.view.findViewById(R.id.publishYearInSearchResult);

            //set Text!
            bookNameInSearchResult.setText(searchResultArrayList.get(position).getBook() + " " + searchResultArrayList.get(position).getAuthor());
            ISBNInSearchResult.setText("ISBN: " + searchResultArrayList.get(position).getISBN());
            publishYearInSearchResult.setText("出版年: " + searchResultArrayList.get(position).getYear());

            setAnimation(viewHolder.container, position);

        }


        //return the size of your dataset
        @Override
        public int getItemCount() {
            return searchResultArrayList.size();
        }

        /**
         * Here is the key method to apply the animation
         */
        private void setAnimation(View viewToAnimate, int position)
        {
            // If the bound view wasn't previously displayed on screen, it's animated
            if (position > lastPosition)
            {
                Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.fade_in);
                viewToAnimate.startAnimation(animation);
                lastPosition = position;
            }
        }
    }
}
