public class Alerts {
    // Date format for recent alerts display
    public static final String DATE_FORMAT = "HH:mm:ss (dd/MM/yy)";

    // Time to wait before calling finish() on AlertPopup after POST_IMPACT_WAIT_MINUTES passed
    public static final int ALERT_POPUP_DONE_PADDING = 10;

    // Time that must pass (in seconds) in between alerts for the same zone (to avoid duplicate alerts)
    public static final int DUPLICATE_ALERTS_PADDING_TIME = 60 * 2;

} public class Safety {
    // The number of minutes to count to after the rocket impact countdown is over
    public static int POST_IMPACT_WAIT_MINUTES = 10;
} public class AlertTypes {
    public static final String SYSTEM = "system";
    public static final String PRIMARY = "alert";
    public static final String SECONDARY = "secondary_alert";

    public static final String TEST = "test";
    public static final String TEST_SOUND = "test_sound";
    public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
} public class AlertPopupParameters {
    public static final String ALERT_CITY = "AlertCity";
} public class SoundLogic {
    static MediaPlayer mPlayer;
    static final int ALARM_CUTOFF_SECONDS = 5;

    public static boolean shouldPlayAlertSound(String alertType, Context context) {
        // No type?
        if (StringUtils.stringIsNullOrEmpty(alertType)) {
            return false;
        }

        // No sound for system message
        if (alertType.equals(AlertTypes.SYSTEM)) {
            return false;
        }

        // Get the audio manager
        AudioManager audioManager = (AudioManager) context.getSystemService(context.AUDIO_SERVICE);

        // Phone is on silent?
        if (audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            // Override silent mode not allowed?
            if (!shouldOverrideSilentMode(alertType, context)) {
                return false;
            }
        }

        // Play sound
        return true;
    }

    public static int getSoundStreamType(Context context) {
        // Get the audio manager
        AudioManager audioManager = (AudioManager) context.getSystemService(context.AUDIO_SERVICE);

        // In call?
        if (audioManager.getMode() == AudioManager.MODE_IN_CALL) {
            // Play in tiny speaker
            // I think we disabled this because it's played in that speaker already by default
            // return AudioManager.STREAM_VOICE_CALL;
        }

        // Return default stream type
        return Sound.STREAM_TYPE;
    }

    public static Uri getAlertSound(String alertType, String overrideSound, Context context) {
        // Override sound selection?
        if (overrideSound != null) {
            // Convert to URI and return it
            return getSoundURI(overrideSound, context);
        }

        // Get selected sound
        String soundPreference = getSoundPreference(alertType, context);

        // Get sound file path
        String selectedSound = Singleton.getSharedPreferences(context).getString(soundPreference, getDefaultSound(alertType, context));

        // No sound selected?
        if (StringUtils.stringIsNullOrEmpty(selectedSound)) {
            // Nothing to play
            return null;
        }

        // Get path to sound resource
        return getSoundURI(selectedSound, context);
    }

    static Uri getSoundURI(String uri, Context context) {
        // No URI? Nothing to do here
        if (StringUtils.stringIsNullOrEmpty(uri)) {
            return null;
        }

        // Support for old alarms (without the scheme identifier)
        if (!uri.contains(Sound.SCHEME_URI_IDENTIFIER)) {
            return getAppSoundByResourceName(uri, context);
        }

        // Scheme without an actual file?
        if (uri.equals(Sound.APP_SOUND_PREFIX)) {
            return null;
        }

        // com.red.alert:// scheme support
        String soundPrefix = Sound.APP_SOUND_PREFIX;

        // Does it start with this prefix?
        if (uri.startsWith(soundPrefix)) {
            // Extract sound resource name without scheme
            uri = uri.substring(uri.indexOf(soundPrefix) + soundPrefix.length());

            // Convert to resource URI
            return getAppSoundByResourceName(uri, context);
        }

        // Try to parse the URI
        return Uri.parse(uri);
    }

    static Uri getAppSoundByResourceName(String resourceName, Context context) {
        // Convert to resource ID
        int resourceID = context.getResources().getIdentifier("raw/" + resourceName, "raw", context.getPackageName());

        // Finally, get path to sound file
        Uri alarmSoundURI = Uri.parse("android.resource://" + context.getPackageName() + "/" + resourceID);

        // Return sound URI
        return alarmSoundURI;
    }

    static String getDefaultSound(String alertType, Context context) {
        // By default, regular sound
        String soundDefault = context.getString(R.string.defaultSound);

        // Secondary alert?
        if (alertType.equals(AlertTypes.SECONDARY)) {
            // Set new value
            soundDefault = context.getString(R.string.defaultSecondarySound);
        }

        // Return default sound
        return soundDefault;
    }

    static String getSoundPreference(String alertType, Context context) {
        // By default, primary preference
        String soundPreference = context.getString(R.string.soundPref);

        // Secondary alert?
        if (alertType.equals(AlertTypes.SECONDARY)) {
            // Set new pref
            soundPreference = context.getString(R.string.secondarySoundPref);
        }

        // Return default pref
        return soundPreference;
    }

    public static boolean shouldOverrideSilentMode(String alertType, Context context) {
        // Testing?
        if (alertType.equals(AlertTypes.TEST_SOUND) || alertType.equals(AlertTypes.TEST_SECONDARY_SOUND)) {
            return true;
        }

        // Get enabled / disabled setting
        boolean overrideSilentMode = Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.silentOverridePref), true);

        // Secondary alert?
        if (alertType.equals(AlertTypes.SECONDARY)
                || alertType.equals(AlertTypes.TEST_SECONDARY_SOUND)) {
            overrideSilentMode = Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondarySilentOverridePref), false);
        }

        // Return setting value
        return overrideSilentMode;
    }

    public static boolean isSoundCurrentlyPlaying(String alertType, Context context) {
        // Primary rocket notification?
        if (alertType.equals(AlertTypes.PRIMARY)) {
            return primaryAlertCurrentlyPlaying(context);
        }

        // Secondary rocket notification?
        if (alertType.equals(AlertTypes.SECONDARY)) {
            return secondaryAlertCurrentlyPlaying(context);
        }

        // Not playing
        return false;
    }

    public static boolean secondaryAlertCurrentlyPlaying(Context context) {
        // Set currently playing
        boolean currentlyPlaying = false;

        // Do we have an alert currently playing? (Played in last X sec)
        if (getAlertLastPlayedTimestamp(context.getString(R.string.lastAlertPref), context) > getCurrentPlayingAlertCutoff()) {
            currentlyPlaying = true;
        }

        // Do we have a sound currently playing? (Played in last X sec)
        if (getAlertLastPlayedTimestamp(context.getString(R.string.lastSecondaryAlertPref), context) > getCurrentPlayingAlertCutoff()) {
            currentlyPlaying = true;
        }

        // Save current timestamp
        saveAlertCurrentlyPlaying(context.getString(R.string.lastSecondaryAlertPref), context);

        // No sound playing
        return currentlyPlaying;
    }

    public static boolean primaryAlertCurrentlyPlaying(Context context) {
        // Set currently playing
        boolean currentlyPlaying = false;

        // Do we have a sound currently playing? (Played in last X sec)
        if (getAlertLastPlayedTimestamp(context.getString(R.string.lastAlertPref), context) > getCurrentPlayingAlertCutoff()) {
            currentlyPlaying = true;
        }

        // Save current timestamp
        saveAlertCurrentlyPlaying(context.getString(R.string.lastAlertPref), context);

        // No sound playing
        return currentlyPlaying;
    }

    static void saveAlertCurrentlyPlaying(String preference, Context context) {
        // Edit shared preferences
        SharedPreferences.Editor edit = Singleton.getSharedPreferences(context).edit();

        // Store current ms in settings with the given property,
        // so that listeners will be notified
        edit.putLong(preference, System.currentTimeMillis());

        // Save and flush
        edit.commit();
    }

    static long getAlertLastPlayedTimestamp(String preference, Context context) {
        // Get last played from preferences
        return Singleton.getSharedPreferences(context).getLong(preference, 0);
    }

    static long getCurrentPlayingAlertCutoff() {
        // Alarm played in past X seconds?
        return System.currentTimeMillis() - (1000 * ALARM_CUTOFF_SECONDS);
    }

    public static void playSound(String alertType, String alertSound, Context context) {
        // Should we play it?
        if (!shouldPlayAlertSound(alertType, context)) {
            return;
        }

        // Avoid secondary override
        if (isSoundCurrentlyPlaying(alertType, context)) {
            return;
        }

        // Get path to resource
        Uri alarmSoundURI = getAlertSound(alertType, alertSound, context);

        // Invalid sound URI?
        if (alarmSoundURI == null) {
            return;
        }

        // Override volume (Also to set the user's chosen volume)
        VolumeLogic.setStreamVolume(alertType, context);

        // Play sound
        playSoundURI(alarmSoundURI, context);

        // Vibrate depending on type
        Vibration.issueVibration(alertType, context);
    }

    public static void stopSound(Context context) {
        // Got a player?
        if (mPlayer != null) {
            // Still playing?
            if (mPlayer.isPlaying()) {
                // Stop playing
                mPlayer.stop();

                // Reset media player
                mPlayer.reset();
            }

            // Release resources associated
            mPlayer.release();

            // Reinitialize next time
            mPlayer = null;
        }

        // Stop vibration
        Vibration.stopVibration(context);
    }

    static void playSoundURI(Uri alarmSoundUi, Context context) {
        // No URI?
        if (alarmSoundUi == null) {
            return;
        }

        // Already initialized or currently playing?
        stopSound(context);

        // Create new MediaPlayer
        mPlayer = new MediaPlayer();

        // Wake up processor
        mPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK);

        // Set stream type
        mPlayer.setAudioStreamType(getSoundStreamType(context));

        try {
            // Set URI data source
            mPlayer.setDataSource(context, alarmSoundUi);

            // Prepare media player
            mPlayer.prepare();
        }
        catch (Exception exc) {
            // Log it
            Log.e(Logging.TAG, "Media player preparation failed", exc);

            // Show visible error toast
            Toast.makeText(context, exc.toString(), Toast.LENGTH_LONG).show();
        }

        // Actually start playing
        mPlayer.start();
    }
} public class AppPreferences {
    public static boolean getNotificationsEnabled(Context context) {
        // Get saved preference
        return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.enabledPref), true);
    }

    public static boolean getLocationAlertsEnabled(Context context) {
        // Get saved preference
        return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.locationAlertsPref), false);
    }

    public static boolean getSecondaryNotificationsEnabled(Context context) {
        // Get saved preference
        return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondaryEnabledPref), false);
    }

    public static boolean getMiBandIntegrationEnabled(Context context) {
        // Get saved preference
        return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.miBandPref), false);
    }

    public static boolean getTutorialDisplayed(Context context) {
        // Get saved preference
        return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.tutorialPref), false);
    }

    public static boolean getPopupEnabled(Context context) {
        // Get saved preference
        return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.alertPopupPref), true);
    }

    public static void setTutorialDisplayed(Context context) {
        // Update stored value
        Singleton.getSharedPreferences(context).edit().putBoolean(context.getString(R.string.tutorialPref), true).commit();
    }

    public static void setCityLastAlertTime(String city, long timestamp, Context context) {
        // Update last alert timestamp for this city
        Singleton.getSharedPreferences(context).edit().putLong(city, timestamp).commit();
    }

    public static long getCityLastAlert(String city, Context context) {
        // Get last alert timestamp for this city
        return Singleton.getSharedPreferences(context).getLong(city, 0);
    }

    public static float getPrimaryAlertVolume(Context context, float overrideValue) {
        // Override?
        if (overrideValue != -1) {
            return overrideValue;
        }

        // Get stored value
        return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.volumePref), 1.0f);
    }

    public static float getSecondaryAlertVolume(Context context, float overrideValue) {
        // Override?
        if (overrideValue != -1) {
            return overrideValue;
        }

        // Get stored value
        return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.secondaryVolumePref), 1.0f);
    }
} public class RTLSupport {
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static void mirrorActionBar(Activity activity) {
        // Hebrew only
        if (!Localization.isHebrewLocale(activity)) {
            return;
        }

        // Must be Jellybean or newer
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            // Set RTL layout direction
            activity.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
        }
    }

    @SuppressLint("NewApi")
    public static void mirrorDialog(Dialog dialog, Context context) {
        // Hebrew only
        if (!Localization.isHebrewLocale(context)) {
            return;
        }

        try {
            // Get message text view
            TextView message = (TextView) dialog.findViewById(android.R.id.message);

            // Defy gravity
            if (message != null) {
                message.setGravity(Gravity.RIGHT);
            }

            // Get the title of text view
            TextView title = (TextView) dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));

            // Defy gravity
            title.setGravity(Gravity.RIGHT);

            // Get list view (may not exist)
            ListView listView = (ListView) dialog.findViewById(context.getResources().getIdentifier("select_dialog_listview", "id", "android"));

            // Check if list & set RTL mode
            if (listView != null) {
                listView.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
            }

            // Get title's parent layout
            LinearLayout parent = ((LinearLayout) title.getParent());

            // Get layout params
            LinearLayout.LayoutParams originalParams = (LinearLayout.LayoutParams) parent.getLayoutParams();

            // Set width to WRAP_CONTENT
            originalParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;

            // Defy gravity
            originalParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;

            // Set layout params
            parent.setLayoutParams(originalParams);
        }
        catch (Exception exc) {
            // Log failure to logcat
            Log.d(Logging.TAG, "RTL failed", exc);
        }
    }
} public class Volume {
    public static void setVolumeKeysAction(Activity context) {
        // Set the appropriate alert stream
        context.setVolumeControlStream(Sound.STREAM_TYPE);
    }
} public class StringUtils {
    public static boolean stringIsNullOrEmpty(String inputString) {
        // String is null? return true
        if (inputString == null) {
            return true;
        }

        // String is empty? true
        if (inputString.trim().equals("")) {
            return true;
        }

        // String is not empty
        return false;
    }

    public static String implode(String separator, List<String> data) {
        // No data?
        if (data.size() == 0) {
            return "";
        }

        // Create temp StringBuilder
        StringBuilder builder = new StringBuilder();

        // Loop over list except last item
        for (int i = 0; i < data.size() - 1; i++) {
            // Append current item
            builder.append(data.get(i));

            // Append separator
            builder.append(separator);
        }

        // Add last item without separator
        builder.append(data.get(data.size() - 1));

        // Return string
        return builder.toString();
    }

    public static String regexMatch(String source, String compilePattern) {
        // Compile regex
        Pattern compiledPattern = Pattern.compile(compilePattern);

        // Match against source input
        Matcher matcher = compiledPattern.matcher(source);

        // Prepare match object
        String match = "";

        // Did we find anything?
        if (matcher.find()) {
            // Get first group
            match = matcher.group(1);
        }

        // Return match
        return match;
    }
} public class LocationData {
    private static List<City> mCities;

    /*
    // Zone = דן 161
    // Zone Code = 161
    // City Name = תל אביב
    // City Countdown = 15 שניות
     */

    public static String[] getAllCityNames(Context context) {
        // Check for english locale
        boolean isHebrew = Localization.isHebrewLocale(context);

        // Get all city objects
        List<City> cities = getAllCities(context);

        // Prepare names array
        List<String> names = new ArrayList<>();

        // Loop over cities
        for (City city : cities) {
            // Hebrew?
            if (isHebrew) {
                // Add to list
                names.add(city.name);
            }
            else {
                // Add english name to list
                names.add(city.nameEnglish);
            }
        }

        // Return array
        return names.toArray(new String[names.size()]);
    }

    public static String[] getAllCityValues(Context context) {
        // Prepare cities array
        List<City> cities = getAllCities(context);

        // Prepare array
        List<String> values = new ArrayList<String>();

        // Loop over cities
        for (City city : cities) {
            // Add to list
            values.add(city.value);
        }

        // Return array
        return values.toArray(new String[values.size()]);
    }

    public static String[] getAllCityZones(Context context) {
        // Get user's locale
        boolean isHebrew = Localization.isHebrewLocale(context);

        // Prepare cities array
        List<City> cities = getAllCities(context);

        // Prepare array
        List<String> values = new ArrayList<String>();

        // Loop over cities
        for (City city : cities) {
            // Hebrew?
            if (isHebrew) {
                // Add to list
                values.add(city.zone);
            }
            else {
                // Add to list
                values.add(city.zoneEnglish);
            }
        }

        // Return array
        return values.toArray(new String[values.size()]);
    }

    public static List<City> getAllCities(Context context) {
        // Got it in cache?
        if (mCities != null) {
            return mCities;
        }

        // Initialize the list
        mCities = new ArrayList<>();

        try {
            // Open the cities.json for reading
            InputStream stream = context.getResources().openRawResource(R.raw.cities);

            // Create a buffered reader
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

            // StringBuilder for efficiency
            StringBuilder builder = new StringBuilder();

            // A temporary variable to store current line
            String currentLine;

            // Read all lines
            while ((currentLine = reader.readLine()) != null) {
                // Append to builder
                builder.append(currentLine);
            }

            // Convert to string
            String json = builder.toString();

            // Convert to city objects
            mCities = Singleton.getJackson().readValue(json, new TypeReference<List<City>>() {
            });
        }
        catch (Exception exc) {
            // Log it
            Log.e(Logging.TAG, "Failed to load cities.json", exc);
        }

        // Return them
        return mCities;
    }

    public static String getSelectedCityNamesByValues(Context context, String selection, CharSequence[] names, CharSequence[] values) {
        // No value? All cities are selected
        if (StringUtils.stringIsNullOrEmpty(selection) || selection.equals(context.getString(R.string.all))) {
            return context.getString(R.string.allString);
        }

        // Value equals none | null?
        else if (selection.equals(context.getString(R.string.none)) || selection.equals(context.getString(R.string.nullString))) {
            return context.getString(R.string.noneString);
        }

        // Display names
        List<String> selectedCityNames = new ArrayList<String>();

        // Remove area code
        String[] selectedValues = selection.split("\\|");

        // Loop over values
        for (String selectedValue : selectedValues) {
            // Loop over values
            for (int i = 0; i < values.length; i++) {
                // Got the value?
                if (values[i].equals(selectedValue)) {
                    // Add the name to list
                    selectedCityNames.add(names[i].toString());
                }
            }
        }

        // Failed to find cities?
        if (selectedCityNames.size() == 0) {
            // Return "none"
            return context.getString(R.string.noneString);
        }

        // Implode into a CSV string
        String displayText = StringUtils.implode(", ", selectedCityNames);

        // Truncate if too long
        if (displayText.length() > 120) {
            displayText = displayText.substring(0, 120) + "...";
        }

        // Return display text
        return displayText;
    }

    public static String getLocalizedZoneWithCountdown(String cityName, Context context) {
        // Get user's locale
        boolean isHebrew = Localization.isHebrewLocale(context);

        // Prepare cities array
        List<City> cities = getAllCities(context);

        // Loop over cities
        for (City city : cities) {
            // Got a match?
            if (city.name.equals(cityName)) {
                // Hebrew?
                if (isHebrew) {
                    // Return area countdown
                    return city.zone + " (" + city.time + ")";
                }
                else {
                    // Return area countdown in English
                    return city.zoneEnglish  + " (" + city.timeEnglish + ")";
                }
            }
        }

        // No match
        return "";
    }

    public static int getCityCountdown(String cityName, Context context) {
        // Prepare cities array
        List<City> cities = getAllCities(context);

        // Loop over cities
        for (City city : cities) {
            // Got a match?
            if (city.name.equals(cityName)) {
                // Return countdown
                return city.countdown;
            }
        }

        // No match
        return 0;
    }

    public static String getLocalizedCityName(String cityName, Context context) {
        // Get user's locale
        boolean isHebrew = Localization.isHebrewLocale(context);

        // Hebrew?
        if (isHebrew) {
            return cityName;
        }

        // Prepare cities array
        List<City> cities = getAllCities(context);

        // Loop over cities
        for (City city : cities) {
            // Got a match?
            if (city.name.equals(cityName)) {
                // Return english name
                return city.nameEnglish;
            }
        }

        // No match
        return cityName;
    }

    public static City getCityByName(String cityName, Context context) {
        // Prepare cities array
        List<City> cities = getAllCities(context);

        // Loop over cities
        for (City city : cities) {
            // Got a match?
            if (city.name.equals(cityName)) {
                return city;
            }
        }

        // No match
        return null;
    }

    public static String getNearbyCityNames(Location myLocation, Context context) {
        // Get user's locale
        boolean isHebrew = Localization.isHebrewLocale(context);

        // Prepare cities array
        List<City> cities = getAllCities(context);

        // Output array
        List<String> cityNames = new ArrayList<>();

        // Calculate max distance
        double maxDistance = LocationLogic.getMaxDistanceKilometers(context, -1);

        // String is not empty
        for (City city : cities) {
            // Prepare new location
            Location location = new Location("");

            // Set lat & long
            location.setLatitude(city.latitude);
            location.setLongitude(city.longitude);

            // Get distance to city in KM
            float distance = location.distanceTo(myLocation) / 1000;

            // Distance is less than max?
            if (distance <= maxDistance) {
                // Hebrew?
                if (isHebrew) {
                    // Add to list
                    cityNames.add(city.name);
                }
                else {
                    // Add to list
                    cityNames.add(city.nameEnglish);
                }
            }
        }

        // Join and add original code
        return StringUtils.implode(", ", cityNames);
    }

    public static Location getCityLocation(String cityName, Context context) {
        // Prepare cities array
        List<City> cities = getAllCities(context);

        // Loop over cities
        for (City city : cities) {
            // Got a match?
            if (city.name.equals(cityName)) {
                // Prepare new location
                Location location = new Location(LocationManager.PASSIVE_PROVIDER);

                // Set lat & long
                location.setLatitude(city.latitude);
                location.setLongitude(city.longitude);

                // Add to list
                return location;
            }
        }

        // Fail
        return null;
    }

    public static List<String> explodeCitiesPSV(String citiesPSV) {
        // Unique cities list
        List<String> uniqueList = new ArrayList<>();

        // Explode into array
        List<String> psvList = Arrays.asList(citiesPSV.split("\\|"));

        // Loop over items
        for (String item : psvList) {
            // Not already added?
            if (!StringUtils.stringIsNullOrEmpty(item) && !uniqueList.contains(item) && !item.equals("none") && !item.equals("null")) {
                // Add it
                uniqueList.add(item);
            }
        }

        // Return them
        return uniqueList;
    }

    public static String getZoneByCityName(String cityName, Context context) {
        // Prepare cities array
        List<City> cities = getAllCities(context);

        // Loop over cities
        for (City city : cities) {
            // Got a match?
            if (city.name.equals(cityName)) {
                return city.zone;
            }
        }

        // Unknown city
        return "";
    }

    public static String getLocalizedZoneByCityName(String cityName, Context context) {
        // Get user's locale
        boolean isHebrew = Localization.isHebrewLocale(context);

        // Prepare cities array
        List<City> cities = getAllCities(context);

        // Loop over cities
        for (City city : cities) {
            // Got a match?
            if (city.name.equals(cityName)) {
                return isHebrew ? city.zone: city.zoneEnglish;
            }
        }

        // Unknown city
        return "";
    }
} public class DensityUtil {
    public static int convertDPToPixels(Context context, int dps) {
        // Get scale
        float scale = context.getResources().getDisplayMetrics().density;

        // Calculate pixels
        return (int) (dps * scale + 0.5f);
    }
}
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.red.alert.R;
import com.red.alert.config.Alerts;
import com.red.alert.config.Safety;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.logic.communication.intents.AlertPopupParameters;
import com.red.alert.logic.feedback.sound.SoundLogic;
import com.red.alert.logic.settings.AppPreferences;
import com.red.alert.ui.localization.rtl.RTLSupport;
import com.red.alert.utils.feedback.Volume;
import com.red.alert.utils.formatting.StringUtils;
import com.red.alert.utils.metadata.LocationData;
import com.red.alert.utils.ui.DensityUtil;
import java.util.Timer;
import java.util.TimerTask;
package com.red.alert.activities;




public class AlertPopup extends AppCompatActivity {
    boolean mIsDestroyed;

    TextView mZone;
    TextView mCounter;

    Button mClose;
    Button mSilence;

    public static void showAlertPopup(String alertType, String city, Context context) {
        // User disabled this feature?
        if (!AppPreferences.getPopupEnabled(context)) {
            // Stop execution
            return;
        }

        // Type must be an "alert"
        if (!alertType.equals(AlertTypes.PRIMARY)) {
            // Stop execution
            return;
        }

        // Create new popup intent
        Intent popupIntent = new Intent();

        // Set class to popup activity
        popupIntent.setClass(context, AlertPopup.class);

        // Pass on zone
        popupIntent.putExtra(AlertPopupParameters.ALERT_CITY, city);

        // Clear top, set as new task
        popupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        popupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        popupIntent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

        // Display popup activity
        context.startActivity(popupIntent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Load UI elements
        initializeUI();

        // Populate UI elements
        initializeAlert();

        // Volume keys should control alert volume
        Volume.setVolumeKeysAction(this);
    }

    void initializeUI() {
        // RTL action bar hack
        RTLSupport.mirrorActionBar(this);

        // Set up UI
        setContentView(R.layout.popup);

        // Cache UI objects
        mClose = (Button) findViewById(R.id.close);
        mSilence = (Button) findViewById(R.id.silence);
        mZone = (TextView) findViewById(R.id.zone);
        mCounter = (TextView) findViewById(R.id.counter);

        // Set up listeners
        initializeListeners();
    }

    void initializeListeners() {
        // Close button clicked
        mClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Stop the media service
                SoundLogic.stopSound(AlertPopup.this);

                // Close popup
                finish();
            }
        });

        // Silence button clicked
        mSilence.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Stop the media service
                SoundLogic.stopSound(AlertPopup.this);
            }
        });
    }

    void initializeAlert() {
        // Get alert city
        String city = getIntent().getStringExtra(AlertPopupParameters.ALERT_CITY);

        // None given?
        if (StringUtils.stringIsNullOrEmpty(city)) {
            return;
        }

        // Set title to city name
        setTitle(LocationData.getLocalizedCityName(city, this));

        // Get zone
        String zone = LocationData.getLocalizedZoneByCityName(city, this);

        // Unknown?
        if (StringUtils.stringIsNullOrEmpty(zone)) {
            return;
        }

        // Set cities to region cities
        mZone.setText(zone);

        // Get countdown in seconds
        int countdown = LocationData.getCityCountdown(city, this);

        // Start counting down
        scheduleRocketCountdown(countdown);
    }

    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();

        // End activity
        if (!isFinishing()) {
            finish();
        }
    }

    void scheduleRocketCountdown(int seconds) {
        // Offset impact to account for delivery delay
        // Seconds = Seconds - Main.IMPACT_COUNTDOWN_OFFSET;

        // Calculate time to impact
        final long impactTimestamp = System.currentTimeMillis() + (seconds * 1000);

        // Schedule a new timer
        new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // Activity died?
                        if (isFinishing() || mIsDestroyed) {
                            return;
                        }

                        // Update countdown
                        updateCountdownTimer(impactTimestamp);
                    }
                });
            }
        }, 0, 100);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // Avoid hiding invalid dialogs
        mIsDestroyed = true;
    }

    void updateCountdownTimer(long impactTimestamp) {
        // Get current time
        long currentTimestamp = System.currentTimeMillis();

        // Calculate seconds left to brace for impact
        int seconds = (int) Math.abs((impactTimestamp - currentTimestamp) / 1000);

        // Did rocket already impact?
        if (currentTimestamp <= impactTimestamp) {
            // Convert it
            updateCountdownTimerText(seconds, R.color.countdown_pre_impact);

        }
        else if (currentTimestamp > impactTimestamp) {
            // Number of seconds to wait after impact
            int postImpactSeconds = (Safety.POST_IMPACT_WAIT_MINUTES * 60);