package com.voicepro.odata;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import org.core4j.Enumerable;
import org.joda.time.LocalDateTime;
import org.odata4j.consumer.ODataConsumer;
import org.odata4j.consumer.behaviors.OClientBehavior;
import org.odata4j.consumer.behaviors.OClientBehaviors;
import org.odata4j.core.OCreateRequest;
import org.odata4j.core.OEntity;
import org.odata4j.core.OEntityKey;
import org.odata4j.core.OPredicates;
import org.odata4j.core.OProperties;
import org.odata4j.jersey.consumer.ODataJerseyConsumer;
import org.odata4j.jersey.consumer.ODataJerseyConsumer.Builder;
import org.restlet.data.ChallengeResponse;
import org.restlet.data.ChallengeScheme;
import org.restlet.ext.odata.Query;

import com.voicepro.MainApplication;
import com.voicepro.R;
import com.voicepro.views.AdvertiseUI;
import android.content.Context;
import android.os.AsyncTask;
import android.provider.Settings.Secure;
import android.util.Log;

public class ODataInteface {

	private ODataConsumer ws;
	private MainApplication app;
	private String httpDataServiceRemote;
	private String httpDataServiceLocale;
	private String httpDownloadLinkRemote;
	private String httpDownloadLinkLocale;
	private Boolean finalResult;
	private Wbvoice4facebookService service;

	public ODataInteface(Context context) throws Exception {
		super();
		app = (MainApplication) context.getApplicationContext();
		
		AdvertiseUI ads = new AdvertiseUI(context);
		
		httpDownloadLinkRemote = new String(ads.unshow(context.getString(R.string.httpDownloadLinkRemote))).trim();
		httpDataServiceRemote =new String(ads.unshow(context.getString(R.string.httpDataServiceRemote))).trim();
		
		//httpDataServiceLocale = "http://192.168.1.103/WBVoice4Facebook/data.svc/";
		//httpDownloadLinkLocale = "http://192.168.1.103/WBVoice4Facebook/DownloadManager.aspx?file=";
		//ODataConsumer.dump.all(true);
		
		final String username = new String(ads.unshow(app.getString(R.string.server_username))).trim();
		final String password = new String(ads.unshow(app.getString(R.string.server_password))).trim();
		
		OClientBehavior cc = OClientBehaviors.basicAuth(username, password);

		Builder builder = ODataJerseyConsumer.newBuilder(httpDataServiceRemote);
		builder.setClientBehaviors(cc);

		ws = builder.build();
		Log.v("wsbuilder", ws.getServiceRootUri());
		
		service = new Wbvoice4facebookService();
		service.setCredentials(
		        new ChallengeResponse(ChallengeScheme.HTTP_BASIC,
		                        "freshup\\Administrator",
		                        "alfonso97_1")
		        );
		
	
	}
	
		

	public ArrayList<CharSequence> Rest_GetCategorie() {
		ArrayList<CharSequence> listaCategorie = new ArrayList<CharSequence>();
		Query<Categorie> query = service.createCategorieQuery("/Categorie").filter("id gt 11");
		for (Categorie cat : query) {
			listaCategorie.add((CharSequence) cat.getName());

		}
		return listaCategorie;
	}
	
//	public ArrayList<CharSequence> getCategorie() {
//		ArrayList<CharSequence> listaCategorie = new ArrayList<CharSequence>();
//		for (OEntity categorie : ws.getEntities("Categorie").filter("id gt 11").execute()) {
//		listaCategorie.add((CharSequence) categorie.getProperty("name").getValue());
//	}
//		return listaCategorie;
//	}
	
	
	
	public ArrayList<BraniCatalog> Res_GetLista() {
		ArrayList<BraniCatalog> lista = new ArrayList<BraniCatalog>();
		Query<Brani> query = service.createBraniQuery("/Brani").filter("categorie_id gt 11");
		for (Brani cat : query) {
			BraniCatalog brano = new BraniCatalog();
			brano.id = cat.getId();
			brano.name = cat.getName();
			brano.description =cat.getDescription();
			brano.categorie_id = cat.getCategorie_id();
			brano.category = cat.getCategorie();
			brano.link = httpDownloadLinkRemote + cat.getTicket();
			brano.price = cat.getPrice();
			lista.add(brano);
			Log.v("Brano:", cat.getName());

		}
		
		return lista;
		
	}

//	public ArrayList<BraniCatalog> getLista() {
//		ArrayList<BraniCatalog> lista = new ArrayList<BraniCatalog>();
//		Enumerable<OEntity> oEntity = ws.getEntities("Brani").filter("categorie_id gt 11").execute();
//
//		for (OEntity brani : oEntity) {
//				BraniCatalog brano = new BraniCatalog();
//				brano.id = brani.getProperty("ID").getValue().toString();
//				brano.name = brani.getProperty("name").getValue().toString();
//				brano.description = (String) brani.getProperty("Description").getValue();
//				brano.categorie_id = brani.getProperty("categorie_id").getValue().toString();
//				brano.category = brani.getProperty("categorie_id").getValue().toString();
//				brano.link = httpDownloadLinkRemote + brani.getProperty("ticket").getValue().toString();
//				brano.price = brani.getProperty("price").getValue().toString();
//				lista.add(brano);
//				Log.v("Categorie:", brani.getProperty("name").getValue().toString());
//		}
//
//		return lista;
//
//	}
	
	public ArrayList<NewsCatalog> Rest_GetNewsFeed(){
		
		
		try {
			SimpleDateFormat mdfUSDate = new SimpleDateFormat("yyyy-MM-dd");
			Date d = new Date();
			String date = mdfUSDate.format(d);
			
			ArrayList<NewsCatalog> templista = new ArrayList<NewsCatalog>();
			Query<News> query = service.createNewsQuery("/News").filter("expireDate ge datetime'"+ date.toString() + "'").orderBy("ID desc");
				for (News news : query) {
						NewsCatalog n = new NewsCatalog();
						n.ID = (Integer) news.getId();
						n.news1 =(String) news.getNews1();
						n.publishDate = news.getPublishDate();
						n.expireDate = news.getExpireDate();
						templista.add(n);
				}
				return templista ;
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
//	public ArrayList<NewsCatalog> GetNewsFeed(){
//		
//		try {
//			SimpleDateFormat mdfUSDate = new SimpleDateFormat("yyyy-MM-dd");
//			Date d = new Date();
//			String date = mdfUSDate.format(d);
//			
//			ArrayList<NewsCatalog> templista = new ArrayList<NewsCatalog>();
//				Enumerable<OEntity> oEntity = ws.getEntities("News").filter("expireDate ge datetime'"+ date.toString() + "'").orderBy("ID desc").execute();
//				for (OEntity news : oEntity) {
//						NewsCatalog n = new NewsCatalog();
//						n.ID = (Integer) news.getProperty("ID").getValue();
//						n.news1 =(String) news.getProperty("news1").getValue();
//						n.publishDate = (LocalDateTime) news.getProperty("publishDate").getValue();
//						n.expireDate =(LocalDateTime) news.getProperty("expireDate").getValue();
//						templista.add(n);
//				}
//				return templista ;
//		} catch (RuntimeException e) {
//			e.printStackTrace();
//		}
//		return null;
//			
//				
//		}
	

	public Boolean Rest_AddUsersForGift() {

	
		
		new AsyncTask<Integer, Integer, Integer>() {
	
			@Override
			protected void onPostExecute(Integer result) {
				if(result==1){
					app.prefs.edit().putBoolean("prefs_problemsWithRatethisApp", false).commit();
				}else{
					app.prefs.edit().putBoolean("prefs_problemsWithRatethisApp", true).commit();
				}
				super.onPostExecute(result);
			}

			@Override
			protected Integer doInBackground(Integer... params) {
				if (app.checkInternetConnection()) {
					String deviceId = Secure.getString(app.getContentResolver(), Secure.ANDROID_ID);

					if (deviceId == null) {
						deviceId = "NULL";
					}
					Query<Users> query = service.createUsersQuery("/Users").filter("DeviceID eq '" + deviceId +"'");
					int count = query.inlineCount(true).getCount();
					
					
					if (count == 0) {
						try {
							Users u = new Users();
							u.setDeviceId(deviceId);
							u.setEmail(app.prefs.getString("acra.user.email", "NULL"));
							u.setCountry(app.getResources().getConfiguration().locale.getDisplayCountry());

							Date datetime = new Date();
							u.setIntallationData(datetime);
						
							// TODO:al Giapponese crashia qui.
							service.addEntity(u);
							Log.v("ODataInteface", "User added successfully");
							return 1;
						} catch (Exception e) {
							e.printStackTrace();
							return 0;
						}

					} else {
						Log.v("ODataInteface", "User already exist, will not be add.");
					}
				} else {
					Log.e("ODataInteface", "Internet connection problem during the AddUserForGift Method");
				}
				
				return 0;
			
			}
			
		}.execute(1);
		
	

		return finalResult;

	}
	
	
//	public Boolean AddUsersForGift() {
//
//	
//		
//		new AsyncTask<Integer, Integer, Integer>() {
//	
//			@Override
//			protected void onPostExecute(Integer result) {
//				if(result==1){
//					app.prefs.edit().putBoolean("prefs_problemsWithRatethisApp", false).commit();
//				}else{
//					app.prefs.edit().putBoolean("prefs_problemsWithRatethisApp", true).commit();
//				}
//				super.onPostExecute(result);
//			}
//
//			@Override
//			protected Integer doInBackground(Integer... params) {
//				if (app.checkInternetConnection()) {
//					String deviceId = Secure.getString(app.getContentResolver(), Secure.ANDROID_ID);
//
//					if (deviceId == null) {
//						deviceId = "NULL";
//					}
//					Enumerable<OEntity> userExist = ws.getEntities("Users").execute().where(OPredicates.entityPropertyValueEquals("DeviceID", deviceId));
//					if (userExist.count() == 0) {
//						try {
//							OCreateRequest<OEntity> cat = ws.createEntity("Users");
//							cat.properties(OProperties.string("DeviceID", deviceId));
//							cat.properties(OProperties.string("Email", app.prefs.getString("acra.user.email", "NULL")));
//							String country = app.getResources().getConfiguration().locale.getDisplayCountry();
//							cat.properties(OProperties.string("Country", country));
//
//							Calendar datetime = Calendar.getInstance();
//							cat.properties(OProperties.datetime("IntallationData", datetime));
//						
//							// TODO:al Giapponese crashia qui.
//							OEntity result = cat.execute();
//							OEntityKey id = result.getEntityKey();
//							Log.v("ODataInteface", "User added successfully");
//							return 1;
//						} catch (Exception e) {
//							e.printStackTrace();
//							return 0;
//						}
//
//					} else {
//						Log.v("ODataInteface", "User already exist, will not be add.");
//					}
//				} else {
//					Log.e("ODataInteface", "Internet connection problem during the AddUserForGift Method");
//				}
//				
//				return 0;
//			
//			}
//			
//		}.execute(1);
//		
//	
//
//		return finalResult;
//
//	}

}
