/*
 * Copyright (c) 2016, 2017 Oracle and/or its affiliates.  All rights reserved.
 *
 * This software is dual-licensed to you under the MIT License (MIT) and
 * the Universal Permissive License (UPL).  See the LICENSE file in the root
 * directory for license terms.  You may choose either license, or both.
 */

package com.oracle.iot.sample.enterpriseclientsample;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.oracle.iot.sample.R;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;

import oracle.iot.client.enterprise.EnterpriseClient;
import oracle.iot.client.enterprise.Pageable;
import oracle.iot.client.enterprise.UserAuthenticationException;

public class DeviceModelListActivity extends Activity {
    ArrayList<DeviceModelLineItem> deviceModels = new ArrayList<DeviceModelLineItem>();
    deviceModelListAdapter dataAdapter = null;
    private static final String ERROR_TAG = "IOT_ERROR";
    Context context;
    private static final String[] supportedDMs = {
            "urn:com:oracle:iot:device:humidity_sensor",
            "urn:com:oracle:iot:device:temperature_sensor",
            "urn:com:oracle:iot:device:motion_activated_camera",
            "urn:com:oracle:iot:device:location:ibeacon",
            "urn:com:oracle:iot:device:location:eddystone-tlm-uid"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_model_list);
        context = this;
        EnterpriseClientUtil util = EnterpriseClientUtil.getInstance(this);
        util.setCurrentContext(this);
        new ECLDeviceTask().execute(this);
    }

    private class ECLDeviceTask extends AsyncTask<Context, String, Void> {
        private Context context;

        @Override
        protected Void doInBackground(Context... params) {
            context = params[0];
            getDeviceModels();
            publishProgress(" ");
            return null;
        }

        public void getDeviceModels(){
            // use enterprise client to get device models
            try {
                EnterpriseClient client = EnterpriseClientUtil.getInstance(null).getECL();
                Pageable<String> tmpModels;
                if (client == null){
                    tmpModels = null;
                    Log.d(ERROR_TAG, "No Enterprise client created with this Name");
                }else
                    tmpModels = client.getDeviceModels();
                if (tmpModels != null) {
                    while (tmpModels.hasMore()) {
                        tmpModels = tmpModels.next();
                        for (String urn : tmpModels.elements()) {
                            if (Arrays.asList(supportedDMs).contains(urn)) {
                                DeviceModelLineItem dmli = new DeviceModelLineItem();
                                dmli.model = client.getDeviceModel(urn);
                                dmli.urn = urn;
                                dmli.name = dmli.model.getName();
                                deviceModels.add(dmli);
                            }
                        }
                    }
                }
            } catch (UserAuthenticationException uae){
                Log.d(ERROR_TAG, uae.getMessage());
                uae.printStackTrace();
            }catch (IOException e) {
                Log.d(ERROR_TAG, e.getMessage());
                e.printStackTrace();
            } catch (GeneralSecurityException e) {
                Log.d(ERROR_TAG, e.getMessage());
                e.printStackTrace();
            }
        }
        @Override
        protected void onPostExecute(Void o) {
            dataAdapter = new deviceModelListAdapter(context,
                    R.layout.model_list_line_item, deviceModels);
            ListView listView = (ListView) findViewById(R.id.modelList);
            // Assign adapter to ListView
            listView.setAdapter(dataAdapter);
        }
    }

    private class deviceModelListAdapter extends ArrayAdapter<DeviceModelLineItem> {

        private ArrayList<DeviceModelLineItem> deviceModelList;

        public deviceModelListAdapter(Context context, int textViewResourceId,
                                      ArrayList<DeviceModelLineItem> dmList) {
            super(context, textViewResourceId, dmList);
            deviceModelList = new ArrayList<DeviceModelLineItem>();
            deviceModelList.addAll(dmList);
        }

        private class ViewHolder {
            TextView name;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;

            if (convertView == null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(
                        Context.LAYOUT_INFLATER_SERVICE);
                convertView = vi.inflate(R.layout.model_list_line_item, null);

                holder = new ViewHolder();
                holder.name = (TextView) convertView.findViewById(R.id.modelTextView);
                convertView.setTag(holder);

                holder.name.setOnClickListener( new View.OnClickListener() {
                    public void onClick(View v) {
                        TextView tv = (TextView) v ;
                        DeviceModelLineItem deviceModelLineItem = (DeviceModelLineItem)tv.getTag();
                        EnterpriseClientUtil.getInstance(null).setDM(deviceModelLineItem);
                        Intent intent = new Intent(context, DeviceListActivity.class);
                        startActivity(intent);
                    }
                });
            }
            else {
                holder = (ViewHolder) convertView.getTag();
            }

            DeviceModelLineItem deviceModelLineItem = deviceModelList.get(position);
            String spaceAdded ="";
            for(int i=deviceModelLineItem.name.length();i<30;i++)
                spaceAdded=spaceAdded+" ";
            holder.name.setText(deviceModelLineItem.name+spaceAdded+">");
            holder.name.setTag(deviceModelLineItem);
            return convertView;
        }
    }
}
