/*
 * FlightIntel for Pilots
 *
 * Copyright 2012 Nadeem Hasan <nhasan@nadmm.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.nadmm.airports.wx;
import java.util.Locale;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.nadmm.airports.DatabaseManager;
import com.nadmm.airports.DatabaseManager.Airports;
import com.nadmm.airports.DatabaseManager.Awos1;
import com.nadmm.airports.DatabaseManager.Wxs;
import com.nadmm.airports.DrawerActivityBase;
import com.nadmm.airports.FragmentBase;
import com.nadmm.airports.R;
import com.nadmm.airports.utils.CursorAsyncTask;
import com.nadmm.airports.utils.FormatUtils;
import com.nadmm.airports.utils.GeoUtils;
import com.nadmm.airports.utils.TimeUtils;
import com.nadmm.airports.wx.Taf.Forecast;
import com.nadmm.airports.wx.Taf.IcingCondition;
import com.nadmm.airports.wx.Taf.TurbulenceCondition;
public class TafFragment extends FragmentBase {
    private final String mAction = NoaaService.ACTION_GET_TAF;
    private final int TAF_RADIUS = 25;
    private final int TAF_HOURS_BEFORE = 3;
    private Location mLocation;
    private IntentFilter mFilter;
    private BroadcastReceiver mReceiver;
    private String mStationId;
    private Forecast mLastForecast;
    @Override
    public void onCreate( Bundle savedInstanceState ) {
        super.onCreate( savedInstanceState );
        setHasOptionsMenu( true );
        mFilter = new IntentFilter();
        mFilter.addAction( mAction );
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive( Context context, Intent intent ) {
                String action = intent.getAction();
                if ( action.equals( mAction ) ) {
                    String type = intent.getStringExtra( NoaaService.TYPE );
                    if ( type.equals( NoaaService.TYPE_TEXT ) ) {
                        showTaf( intent );
                    }
                }
            }
        };
    }
    @Override
    public void onResume() {
        LocalBroadcastManager bm = LocalBroadcastManager.getInstance( getActivity() );
        bm.registerReceiver( mReceiver, mFilter );
        Bundle args = getArguments();
        String stationId = args.getString( NoaaService.STATION_ID );
        setBackgroundTask( new TafTask() ).execute( stationId );
        super.onResume();
    }
    @Override
    public void onPause() {
        LocalBroadcastManager bm = LocalBroadcastManager.getInstance( getActivity() );
        bm.unregisterReceiver( mReceiver );
        super.onPause();
    }
    @Override
    public View onCreateView( LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState ) {
        View view = inflater.inflate( R.layout.taf_detail_view, container, false );
        Button btnGraphic = (Button) view.findViewById( R.id.btnViewGraphic );
        btnGraphic.setOnClickListener( new OnClickListener() {
            @Override
            public void onClick( View v ) {
                Intent intent = new Intent( getActivity(), TafMapActivity.class );
                startActivity( intent );
            }
        } );
        return createContentView( view );
    }
    @Override
    public void onPrepareOptionsMenu( Menu menu ) {
        DrawerActivityBase activity = (DrawerActivityBase) getActivity();
        setRefreshItemVisible( !activity.isNavDrawerOpen() );
    }
    @Override
    public boolean onOptionsItemSelected( MenuItem item ) {
        // Handle item selection
        switch ( item.getItemId() ) {
            case R.id.menu_refresh:
                startRefreshAnimation();
                requestTaf( mStationId, true );
                return true;
            default:
                return super.onOptionsItemSelected( item );
        }
    }
    private final class TafTask extends CursorAsyncTask {
        @Override
        protected Cursor[] doInBackground( String... params ) {
            String stationId = params[ 0 ];
            Cursor[] cursors = new Cursor[ 2 ];
            SQLiteDatabase db = getDbManager().getDatabase( DatabaseManager.DB_FADDS );
            SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
            builder.setTables( Wxs.TABLE_NAME );
            String selection = Wxs.STATION_ID+"=?";
            Cursor c = builder.query( db, new String[] { "*" }, selection,
                    new String[] { stationId }, null, null, null, null );
            c.moveToFirst();
            String siteTypes = c.getString( c.getColumnIndex( Wxs.STATION_SITE_TYPES ) );
            if ( !siteTypes.contains( "TAF" ) ) {
                // There is no TAF available at this station, search for the nearest
                double lat = c.getDouble( c.getColumnIndex( Wxs.STATION_LATITUDE_DEGREES ) );
                double lon = c.getDouble( c.getColumnIndex( Wxs.STATION_LONGITUDE_DEGREES ) );
                Location location = new Location( "" );
                location.setLatitude( lat );
                location.setLongitude( lon );
                c.close();
                // Get the bounding box first to do a quick query as a first cut
                double[] box = GeoUtils.getBoundingBoxRadians( location, TAF_RADIUS );
                double radLatMin = box[ 0 ];
                double radLatMax = box[ 1 ];
                double radLonMin = box[ 2 ];
                double radLonMax = box[ 3 ];
                // Check if 180th Meridian lies within the bounding Box
                boolean isCrossingMeridian180 = ( radLonMin > radLonMax );
                selection = "("
                    +Wxs.STATION_LATITUDE_DEGREES+">=? AND "+Wxs.STATION_LATITUDE_DEGREES+"<=?"
                    +") AND ("+Wxs.STATION_LONGITUDE_DEGREES+">=? "
                    +(isCrossingMeridian180? "OR " : "AND ")+Wxs.STATION_LONGITUDE_DEGREES+"<=?)";
                String[] selectionArgs = {
                        String.valueOf( Math.toDegrees( radLatMin ) ),
                        String.valueOf( Math.toDegrees( radLatMax ) ),
                        String.valueOf( Math.toDegrees( radLonMin ) ),
                        String.valueOf( Math.toDegrees( radLonMax ) )
                        };
                c = builder.query( db, new String[] { "*" }, selection, selectionArgs,
                        null, null, null, null );
                stationId = "";
                if ( c.moveToFirst() ) {
                    float distance = Float.MAX_VALUE;
                    do {
                        siteTypes = c.getString( c.getColumnIndex( Wxs.STATION_SITE_TYPES ) );
                        if ( !siteTypes.contains( "TAF" ) ) {
                            continue;
                        }
                        // Get the location of this station
                        float[] results = new float[ 2 ];
                        Location.distanceBetween(
                                location.getLatitude(),
                                location.getLongitude(),
                                c.getDouble( c.getColumnIndex( Wxs.STATION_LATITUDE_DEGREES ) ),
                                c.getDouble( c.getColumnIndex( Wxs.STATION_LONGITUDE_DEGREES ) ),
                                results );
                        results[ 0 ] /= GeoUtils.METERS_PER_NAUTICAL_MILE;
                        if ( results[ 0 ] <= TAF_RADIUS && results[ 0 ] < distance ) {
                            stationId = c.getString( c.getColumnIndex( Wxs.STATION_ID ) );
                            distance = results[ 0 ];
                        }
                    } while ( c.moveToNext() );
                }
            }
            c.close();
            if ( stationId.length() > 0 ) {
                // We have the station with TAF
                builder = new SQLiteQueryBuilder();
                builder.setTables( Wxs.TABLE_NAME );
                selection = Wxs.STATION_ID+"=?";
                c = builder.query( db, new String[] { "*" }, selection,
                        new String[] { stationId }, null, null, null, null );
                cursors[ 0 ] = c;
                String[] wxColumns = new String[] {
                        Awos1.WX_SENSOR_IDENT,
                        Awos1.WX_SENSOR_TYPE,
                        Awos1.STATION_FREQUENCY,
                        Awos1.SECOND_STATION_FREQUENCY,
                        Awos1.STATION_PHONE_NUMBER,
                        Airports.ASSOC_CITY,
                        Airports.ASSOC_STATE
                };
                builder = new SQLiteQueryBuilder();
                builder.setTables( Airports.TABLE_NAME+" a"
                        +" LEFT JOIN "+Awos1.TABLE_NAME+" w"
                        +" ON a."+Airports.FAA_CODE+" = w."+Awos1.WX_SENSOR_IDENT );
                selection = "a."+Airports.ICAO_CODE+"=?";
                c = builder.query( db, wxColumns, selection, new String[] { stationId },
                        null, null, null, null );
                cursors[ 1 ] = c;
            }
            return cursors;
        }
        @Override
        protected boolean onResult( Cursor[] result ) {
            Cursor wxs = result[ 0 ];
            if ( wxs == null || !wxs.moveToFirst() ) {
                // No station with TAF was found nearby
                Bundle args = getArguments();
                String stationId = args.getString( NoaaService.STATION_ID );
                View detail = findViewById( R.id.wx_detail_layout );
                detail.setVisibility( View.GONE );
                LinearLayout layout = (LinearLayout) findViewById( R.id.wx_status_layout );
                layout.removeAllViews();
                layout.setVisibility( View.GONE );


Answer:                 TextView tv =(TextView) findViewById( R.id.status_msg );